Pages

Polymorphism,JAVA



Polymorphism came from the two Greek words ‘poly’ means many and morphos means forms. If the same method has ability to take more than one form to perform several tasks then it is called polymorphism. It is of two types: Dynamic polymorphism and Static polymorphism.
· Dynamic Polymorphism: The polymorphism exhibited at run time is called dynamic polymorphism. In this dynamic polymorphism a method call is linked with method body at the time of execution by JVM. Java compiler does not know which method is called at the time of compilation. This is also known as dynamic binding or run time polymorphism. Method overloading and method overriding are examples of Dynamic Polymorphism in Java.
o Method Overloading: Writing two or more methods with the same name, but with a difference in the method signatures is called method over loading. Method signature represents the method name along with the method parameters. In method over loading JVM understands which method is called depending upon the difference in the method signature. The difference may be due to the following:
Ø  There is a difference in the no. of parameters.
void add (int a,int b) void add (int a,int b,int c)
Ø  There is a difference in the data types of parameters.
void add (int a,float b) void add (double a,double b) 
Ø  There is a difference in the sequence of parameters.
void swap (int a,char b) void swap (char a,int b)

Program 1:  Write a program to create a class which contains two methods with the same name but with different signatures.

 // overloading of methods   --------- Dynamic polymorphism class Sample
{                 void add(int a,int b)
                        {
                                    System.out.println ("sum of two="+ (a+b));
                        }
                        void add(int a,int b,int c)
                        {
                                    System.out.println ("sum of three="+ (a+b+c));
                        }
      }
      class OverLoad
      {                 public static void main(String[] args) 
                    {
                            Sample s=new Sample ( );
                                s.add (20, 25);
                                    s.add (20, 25, 30);
                        }
     
Output:

· Method Overriding: Writing two or more methods in super & sub classes with same name and same signatures is called method overriding. In method overriding JVM executes a method depending on the type of the object.
Program 2: Write a program that contains a super and sub class which contains a method with same name and same method signature, behavior of the method is dynamically decided.
//overriding of methods --------------- Dynamic polymorphism      class Animal
     {      void move()
{
System.out.println ("Animals can move"); }
     }
     class Dog extends Animal
     {      void move()
{
System.out.println ("Dogs can walk and run"); }
     }
     public class OverRide
     {      public static void main(String args[])
{           Animal a = new Animal (); // Animal reference and object
Animal b = new Dog (); // Animal reference but Dog object
             a.move (); // runs the method in Animal class
             b.move (); //Runs the method in Dog class
 }
     }
Output:
 Achieving method overloading & method overriding using instance methods is an example of dynamic polymorphism.

· Static Polymorphism: The polymorphism exhibited at compile time is called Static polymorphism. Here the compiler knows which method is called at the compilation. This is also called compile time polymorphism or static binding. Achieving method overloading & method overriding using private, static and final methods is an example of Static Polymorphism.
Program 3:  Write a program to illustrate static polymorphism.
//Static Polymorphism      class Animal
     {                  static void move ()
{           System.out.println ("Animals can move");
}
      }
      class Dog extends Animal       {                 static void move ()
{           System.out.println ("Dogs can walk and run");
}
      }
      public class StaticPoly
      {                 public static void main(String args[])
{           Animal.move ();
                         Dog.move ();
}
      }
Output:


The keyword ‘final’: 
· final keyword before a class prevents inheritance.
e.g.:   final class A
          class B extends A //invalid    
· final keyword before a method prevents overriding.
· final keyword before a variable makes that variable as a constant.
e.g.:   final double PI = 3.14159; //PI is a constant.

Type Casting: Converting one data type into another data type is called casting. Type cast operator is used to convert one data type into another data type. Data type represents the type of the data stored into a variable.  There are two kinds of data types:

· Primitive Data type:  Primitive data type represents singular values.
e.g.:  byte, short, int, long, float, double, char, boolean.
Using casting we can convert a primitive data type into another primitive data type.  This is done in two ways, widening and narrowing.
o Widening: Converting a lower data type into higher data type is called widening.
byte, short, int, long , float, double e.g.: char ch = 'a';              int n = (int ) ch;             e.g.: int n = 12;                     float f = (float) n;
o Narrowing: Converting a higher data type into lower data type is called narrowing. e.g.: int i = 65;   charch=(char)i;           
e.g.: float f = 12.5; int i = (int) f;
· Referenced Data type:  Referenced data type represents multiple values.
e.g.: class, String

Using casting we can convert one class type into another class type if they are related by means of inheritance.
o Generalization: Moving back from subclass to super class is called generalization or widening or upcasting.
o Specialization: Moving from super class to sub class is called specialization or narrowing or downcasting.

      Program 4: Write a program to convert one class type into another class type.
      // conversion of one class type into another class type      class One
     {                  void show1()
                        {          System.out.println ("One's method");
                        }
     }
     class Two extends One
     {                  void show2()
                        {          System.out.println ("Two's method");
                        }
     }       
     class Ex3
     {                   
public static void main(String args[])
                        {
/* If super class reference is used to refer to super class object then only super class members are available to programmer. */
                                    One ob1 = new One ();             
                                    ob1.show1 ();
/* If sub class reference is used to refer to sub class object then super class members as
well as sub class members are available to the programmer. */
                                    Two ob2 = new Two();                                     ob2.show1();                          ob2.show2();
/* If super class reference is used to refer to sub class object then super class methods are available, sub class methods are not available unless they override super class methods */
                                    One ob3 = (One) new Two();  // Generalization
                                    ob3.show1();
/* It is not possible to access any methods if we use subclass object to refer to super class as above */
                                    Two ob4 = (Two) new One();                                       ob4.show1();                          ob4.show2();  
                        // Specialization
                                    One ob5 = (One) new Two();
                                    Two ob6 = (Two) ob5;                                                              ob6.show1();                          ob6.show2();
                        }
     }

Note: Using casting it is not possible to convert a primitive data type into a referenced data type and vice-versa. For this we are using Wrapper classes.