Learn polymorphism in java

Hey guys!!! Welcome to flower brackets blog. Here we are going to learn polymorphism in java.

Polymorphism is the ability of a method to perform different tasks. Polymorphism literally means having different forms. When you define a  method its property of having many forms is called as polymorphism.

Let’s see an example. I have four classes defined, first one is class “Company” which will be the base class.

class “Company” has method getSharePrice() and this will return share price,

// Base Class
public class Company
{ 
   int getSharePrice()
   {
      return 0; // returns 0 as share price
   }
}

Next I have defined derived classes “CompanyA”, class “CompanyB” and class “CompanyC”.

// Derived Class
public class CompanyA extends Company
{ 
   int getSharePrice()
   {
      return 5;
   }
}

// Derived Class
public class CompanyB extends Company
{ 
   int getSharePrice()
   {
      return 6;
   }
}

// Derived Class
public class CompanyC extends Company
{ 
   int getSharePrice()
   {
      return 10;
   }
}

Above three classes extends the base class “Company” and have defined method getshareprice() in each of the above three classes.

public class PolymorphismExample
{
   public static void main(String[] args)
   {
      Company a = new CompanyA();
      Company b = new CompanyB();
      Company c = new CompanyC();
 
      System.out.println(a.getSharePrice());
      System.out.println(b.getSharePrice());
      System.out.println(c.getSharePrice());
   }
}

Output:

5

6

10

As you can see above code, we have defined reference of class “Company” as ‘a’ and this will point to the object of “CompanyA” which is a derived class or child class.

This is what we call polymorphism. So here the object of class “Company” is having the form of “CompanyA”.

Also read – abstraction in java

So the reference of class “Company” is pointing to the object of class “CompanyA”. In the same way we have defined remaining objects as shown above.

The interesting thing here is all references are pointing to different objects but all objects are from class “Company”.


Types of polymorphism

Polymorphism in java has two types

  • Compile time polymorphism
  • Runtime polymorphism

Compile time polymorphism:

Compile time polymorphism is also called as static binding. It is method overloading technique. In this, class can have more than one method.

In compile time polymorphism we define a method numerous times with same name but with different signature argument. It can be implemented in a single class.

Compiler is able to figure out the method call at compile time that’s the reason it is known as compile time polymorphism. Let’s see an example,

public class StaticBindingDemo
{
   public static void main(String[] args)
   {
      Subtraction sub = new Subtraction();
      sub.subtract(10, 4);     // method call
      sub.subtract(25, 5, 7);  // method call
   }
}

class Subtraction
{
   void subtract(int a, int b)
   {
      System.out.println("Subtracting two integers : " + (a - b));
   }
   void subtract(int m, int n, int o)
   {
      System.out.println("Subtracting three integers : " + (m - n - o));
   }
}

Output:

Subtracting two integers : 6
Subtracting three integers : 13


Runtime polymorphism:

In runtime polymorphism a method is defined in the subclass with same name and same signature as its superclass.

Runtime polymorphism is referred as method overriding. It is also called dynamic binding. Let’s see an example,

NOTE : Runtime polymorphism can be implemented only through IS-A relationship, i.e, through inheritance.

// superclass
public class vehicle
{ 
   public void driving()
   {
      System.out.println("Mr.X is driving vehicle..");
   }
}

// subclass
class Car extends vehicle
{
   @Override
   public void driving()
   {
      System.out.println("Mr.X is driving car..");
   }
}

// subclass
class Lorry extends vehicle
{
   @Override
   public void driving()
   {
      System.out.println("Mr.X is driving lorry..");
   }
 
   public void load()
   {
      System.out.println("Mr.X is loading lorry..");
   }
}

// main
public class RuntimePolymorphismDemo
{
   public static void main(String[] args)
   {
      vehicle v = new vehicle();
      v.driving();
 
      v = new Car();
      v.driving();
 
      v = new Lorry();
      v.driving();
 
      Lorry lr = new Lorry();
      lr.load();
   }
}

Output:

Learn Polymorphism In Java

Vehicle v = new Car();

In the “main” method there are two parts. First is reference variable of superclass and another is constructor of subclass.

The reference variable is vehicle and the object created is of type Car. Above assignment is only possible when object created type is a subclass of the reference type.

That is, in runtime polymorphism overridden method is called through reference variable of superclass. In the above program,

v.driving();

compiles because driving() method is part of class “vehicle” and gives

"Mr.X is driving car.."

as the output because driving() method is overridden by class “Car”. Similarly if you call,

lr.load();

There will be a compile time error because load() method is not part of class “vehicle”, it is defined only in class “Lorry”.

In the above code lr.load() compiles because reference type is class “Lorry” and the compiler can resolve load() method.

The selection of method to execute happens at runtime, that is, which method to execute, that is, parent class or child class is decided at runtime and this leads to runtime polymorphism.


Runtime polymorphism in java with data member

Runtime polymorphism with data member can’t be achieved. Because data member are variables in class and methods are overridden not data members.

class Plants 
{
   int height = 5; 
}

class Basil extends Plants 
{
   int height = 3;

   public static void main(String[] args) 
   {
      Plants obj = new Basil();
      System.out.println(obj.height);
   }
}

Output:

5


Runtime polymorphism in java with multilevel inheritance

class GrandPa
{ 
   void display()
   {
      System.out.println("Grand Parent");
   } 
} 
class Parents extends GrandPa
{ 
   void display()
   {
      System.out.println("Parent");
   } 
} 
class Children extends Parents
{ 
   void display()
   {
      System.out.println("Child");
   } 
   public static void main(String args[])
   { 
      GrandPa obj1 = new GrandPa(); 
      Parents obj2 = new Parents(); 
      Children obj3 = new Children(); 
      obj1.display(); 
      obj2.display(); 
      obj3.display(); 
   } 
}

Output:

Grand Parent

Parent

Child

Related Posts