POLYMORPHISM IN JAVA

Polymorphism in Java is the ability of an object of a class to behave differently. Here "Poly" means many and "morphs" means forms. Example could be mode of communcation, it could be face to face, over phone, over chat or video etc. Hence it can be done in many forms.

Table of Contents

[hide]
  • What is Polymorphism in Java
  • Compile Time Polymorphism
  • Runtime Polymorphism(Dynamic Method Dispatch)
  • Runtime Polymorphism with Data Member

What is Polymorphism in Java

Polymorphism in Java is one of the main key features of Object-Oriented programming . Java Polymorphism can be divided into two parts :

  • 1. Compile time Polymorphism
  • 2. Runtime Polymorphism.
What is Polymorphism in Java

We have already covered these topics in our previous tutorials :

Polymorphism in Java is the ability for a message or data to be processed in more than one form. Especially in Java this definition of polymorphism isn't hard to understand at all. Oh look, various animals make different sounds, and the same process can be used to make each sound different. If you did the Java inheritance guide, you already know how to do it!

REAL WORLD EXAMPLE OF POLYMORPHISM:

  • One of the example of Polymorphism is google search engine, which is just a text box but gives us different kinds of results. We dont have separate search box for different kind of categories.

  • A man takes up multiple roles like, he is a dad to his child, he is a employee,etc etc

  • A Software Engineer performs several activities, as sometimes he performs coding, sometimes he performs testing, sometimes he performs analyzing.

ADVANTAGES :

  • Polymorphism lets programmers reuse the existing code

  • A single variable name can store variables of multiple data types( int, float, double, long, etc).

  • It Increases the readability of the program.

Compile Time Polymorphism

Compile Time Polymorphism is also known as static polymorphism since it is resolved during Compile time. Method Overloading in Java is one such example of Compile Time Polymorphism.

Method overloading in Java implements polymorphism and also reduces number of comparisons in a program and thereby makes the program run faster.

Method Overloading in Java is a mechanism in which different methods are allowed to have the same name if it can be distinguished by their number and type of arguments

Example : Compile Time Polymorphism in Java

copyimage
//Java Program to demonstrate Compile Time Polymorphism in Java
class OverloadingExample {
  public int maximum(int num1, int num2) {
	return num1>num2?num1:num2;
  }

  public int maximum(int num1, int num2, int num3) {
	if (num1 >= num2 && num1 >= num3)
	    return num1;
	else if (num2 >= num1 && num2 >= num3)
	    return num2;
	else
	    return num3;
    }
}
class Codebator  { 
public static void main(String[] args) {
	OverloadingExample obj=new OverloadingExample();
	int maxoftwo = obj.maximum(30,10);
	int maxofthree = obj.maximum(20,50,30);
	System.out.println("maximum of two number is : "+ maxoftwo);
	System.out.println("maximum of three number is : "+ maxofthree);
  }
}

OUTPUT :

maximum of two number is : 40maximum of three number is : 70 

We have already know much about method overloading or we can say compile time polymorphism, now let us focus more on Runtime Polymorphism in Java.

Runtime Polymorphism(Dynamic Method Dispatch)

Runtime Polymorphism is also known as dynamic method Dispatch in which a call to an overriden method is resolved at Runtime rather than compile time.

Before Learning Runtime Polymorphism in Java, let us know about one of the most valuable concept called Upcasting.

UPCASTING IN JAVA

upcasting-in-java

When reference variable in Super Class refers to the Object of Sub Class, it is known as Upcasting. It is the typecasting of a child object to a parent object.

Syntax :

class Parent{
}
class Child extends Parent{
  public static void main(String[] args){
    Parent obj=new Child();//upcasting  
  }
}

The Runtime Polymorphism in Java is used to allow for the specific implementation of a method already supported by its superclass. Method overriding is used to achieve runtime polymorphism, since JVM determines the calling method during runtime.

It is useful when a class has multiple child classes, and if a child class wants to use the parent class method, it can use it, and the other classes that want different implementation can use overriding features to make improvements without touching the parent code.

Example 1 : Runtime Polymorphism in Java

copyimage
//Java Program to demonstrate Runtime Polymorphism in Java
class Bird{
   public void fly(){
      System.out.println("Bird is flying");
   }
}
class Parrot extends Bird{
   public void fly(){
      System.out.println("Parrot is flying");
   }
}
public class Codebator{
   public static void main(String[] args) {
   // Parrot p=new Bird();  Compile Time Error
      Bird p=new Parrot();
      p.fly(); //upcasting
  }
}

OUTPUT :

Parrot is flying

Example 2 : Runtime Polymorphism in Java

copyimage
//Java Program to demonstrate Runtime Polymorphism in Java
class Mobile{
   public void show(){
      System.out.println("Mobile");
   }
}
class IPhone extends Mobile{
   public void show(){
      System.out.println("Mobile IPhone..");
   }
}
class Samsung  extends Mobile{
   public void show(){
      System.out.println("Mobile Samsung..");
   }
}
public class Codebator{
   public static void main(String[] args) {
      Mobile obj;
      obj=new IPhone();
      obj.show();
      obj=new Samsung();
      obj.show();
   }
}

OUTPUT :

Mobile IPhone..Mobile Samsung.. 

Runtime Polymorphism with Data Member

We cannot achieve Runtime Polymorphism with data members , since method is overriden not the data members.

Let us see an example below where both the mobile classes have a data member cost. In the main method be will access the data member with the reference variable of the Parent class which refers to the Child class object.

Because we access the data member that is not overridden, it will always access the Parent class data member.

Example 1 : Runtime Polymorphism in Java with Data members

copyimage
//Java Program to demonstrate Runtime Polymorphism in Java with Data Member
class Mobile{
   int cost=0;
   public void show(){
       System.out.println("Mobile");
   }
}
class IPhone extends Mobile{
   int cost=40000;
   public void show(){
       System.out.println("Mobile IPhone..");
   }
}
class Samsung  extends Mobile{
   int cost=50000;
   public void show(){
      System.out.println("Mobile Samsung..");
   }
}
public class Codebator{
   public static void main(String[] args) {
      Mobile obj;
      obj=new IPhone();
      System.out.println(obj.cost);
      obj=new Samsung();
      System.out.println(obj.cost);
   }
}

OUTPUT :

00 

If you access the cost variable inside an overridden method, then you would be able to see the following result :

Example 2 : Runtime Polymorphism in Java with Data members

copyimage
//Java Program to demonstrate Runtime Polymorphism in Java with Data Member
class Mobile{
   int cost=0;
   public void show(){
       System.out.println("Mobile");
   }
}
class IPhone extends Mobile{
   int cost=40000;
   public void show(){
       System.out.println("Mobile IPhone : "+cost);
   }
}
class Samsung  extends Mobile{
   int cost=50000;
   public void show(){
      System.out.println("Mobile Samsung : "+cost);
   }
}
public class Codebator{
   public static void main(String[] args) {
      Mobile obj;
      obj=new IPhone();
      obj.show();
      obj=new Samsung();
      obj.show();
   }
}

OUTPUT :

Mobile IPhone : 40000Mobile Samsung : 50000 

Now Since we are performing method overrinding, hence the call to an overridden method in invoked and thus we are able to see the values of cost corresponding to the types of Mobile.