Polymorphism in Java OOPs with Example: What is, Dynamic

What is Polymorphism in Java?

Polymorphism in Java occurs when there are one or more classes or objects related to each other by inheritance. It is the ability of an object to take many forms. Inheritance lets users inherit attributes and methods, and polymorphism uses these methods to perform different tasks. So, the goal is communication, but the approach is different.

For example, you have a smartphone for communication. The communication mode you choose could be anything. It can be a call, a text message, a picture message, mail, etc. So, the goal is common that is communication, but their approach is different. This is called Polymorphism. Now, we will learn Polymorphism in Java with example.

In this Java tutorial, you will learn-




Click here if the video is not accessible

Java Polymorphism in OOPs with Example

We have one parent class, ‘Account’ with function of deposit and withdraw. Account has 2 child classes

The operation of deposit and withdraw is same for Saving and Checking accounts. So the inherited methods from Account class will work.

Single Inheritance in Java
Java Polymorphism Example

Change in Software Requirement

There is a change in the requirement specification, something that is so common in the software industry. You are supposed to add functionality privileged Banking Account with Overdraft Facility.

For a background, overdraft is a facility where you can withdraw an amount more than available the balance in your account.

So, withdraw method for privileged needs to implemented afresh. But you do not change the tested piece of code in Savings and Checking account. This is advantage of OOPS

Java Polymorphism

Step 1) Such that when the “withdrawn” method for saving account is called a method from parent account class is executed

Java Polymorphism

Step 2) But when the “Withdraw” method for the privileged account (overdraft facility) is called withdraw method defined in the privileged class is executed. This is Polymorphism in OOPs.

Java Polymorphism

Method Overriding in Java

Method Overriding is redefining a super class method in a sub class.

Rules for Method Overriding

  • The method signature i.e. method name, parameter list and return type have to match exactly.
  • The overridden method can widen the accessibility but not narrow it, i.e. if it is private in the base class, the child class can make it public but not vice versa.

Rules for Method Overriding in Java

Example

class Doctor{
  public void treatPatient(){
  // treatPatient method
  
}
class Surgeon extends Doctor{
  public void treatPatient(){
  // treatPatient method
  }
}
Class run{
  public static void main (String args[]){
    Doctor doctorObj = new Doctor()
	// treatPatient method in class Doctor will be executed
    doctorObj.treatPatient();
   
    Surgeon surgeonObj = new Surgeon();
    // treatPatient  method in class Surgeon  will be executed
    surgeonObj.treatPatient();
  }
}

Difference between Overloading and Overriding

Method Overloading
Method Overriding
Method overloading is in the same class, where more than one method have the same name but different signatures. Method overriding is when one of the methods in the super class is redefined in the sub-class. In this case, the signature of the method remains the same.
Ex:

void sum (int a , int b);
void sum (int a , int b, int c);
void sum (float a, double b);
Ex:

class X{
  public int sum(){
     // some code
  }
}
class Y extends X{
  public int sum(){
    //overridden method
   //signature is same
 }
}

What is Dynamic Polymorphism?

Dynamic Polymorphism in OOPs is the mechanism by which multiple methods can be defined with same name and signature in the superclass and subclass. The call to an overridden method are resolved at run time.

Dynamic Polymorphism Example:

A reference variable of the super class can refer to a sub class object

 Doctor obj = new Surgeon();

Consider the statement

obj.treatPatient();

Here the reference variable “obj” is of the parent class, but the object it is pointing to is of the child class (as shown in the below diagram example of Polymorphism).

obj.treatPatient() will execute treatPatient() method of the sub-class – Surgeon

If a base class reference is used to call a method, the method to be invoked is decided by the JVM, depending on the object the reference is pointing to

For example, even though obj is a reference to Doctor, it calls the method of Surgeon, as it points to a Surgeon object

This is decided during run-time and hence termed dynamic or run-time polymorphism

Difference between Static & Dynamic Polymorphism

Static Polymorphism in Java is a type of polymorphism that collects the information for calling a method at compilation time, whereas Dynamic Polymorphism is a type of polymorphism that collects the information for calling a method at runtime.

Static Polymorphism
Dynamic Polymorphism
It relates to method overloading. It relates to method overriding.
Errors, if any, are resolved at compile time. Since the code is not executed during compilation, hence the name static.

Ex:

void sum (int a , int b);
void sum (float a, double b);
int sum (int a, int b); //compiler gives error.

In case a reference variable is calling an overridden method, the method to be invoked is determined by the object, your reference variable is pointing to. This is can be only determined at runtime when code in under execution, hence the name dynamic.

Ex:

//reference of parent pointing to child object
 Doctor obj = new Surgeon();
// method of child called
obj.treatPatient();

Super Keyword in Java

What if the treatPatient method in the Surgeon class wants to execute the functionality defined in Doctor class and then perform its own specific functionality?

In this case, keyword supercan be used to access methods of the parent class from the child class.

The treatPatient method in the Surgeon class could be written as:

treatPatient(){
   super.treatPatient();
     //add code specific to Surgeon
}

The keyword super can be used to access any data member or methods of the super class in the sub class.

Next, we will learn about Super keyword, Inheritance and Polymorphism in Java with example programs.

Example:-To learn Inheritance, Polymorphism & super keyword

Step 1) Copy the following code into an Editor

public class Test{
     public static void main(String args[]){
        X x= new X();
       Y y = new  Y();
       y.m2();
      //x.m1();
      //y.m1();
     //x = y;// parent pointing to object of child
     //x.m1() ;
     //y.a=10;
   }
}
class X{
   private int a;
   int b;
      public void m1(){
       System.out.println("This is method m1 of class X");
     }
}
class Y extends X{
      int c; // new instance variable of class Y
         public void m1(){
            // overriden method
            System.out.println("This is method m1 of class Y");
        }
       public void m2(){
           super.m1();
           System.out.println("This is method m2 of class Y");
      }
}

Step 2) Save, Compile & Run the code. Observe the output.

Step 3) Uncomments lines # 6-9. Save, Compile & Run the code. Observe the output.

Step 4) Uncomment line # 10 . Save & Compile the code.

Step 5) Error = ? This is because sub-class cannot access private members of the super class.

Summary

  • Polymorphism in Object Oriented Programming occurs when there are one or more classes or objects related to each other by inheritance. It is the ability of an object to take many forms.
  • Method Overriding is redefining a super class method in a sub class.
  • Dynamic Polymorphism in Java is the mechanism by which multiple methods can be defined with same name and signature in the superclass and subclass.
  • Static Polymorphism in Java is a type of polymorphism that collects the information for calling a method at compilation time, whereas Dynamic Polymorphism is a type of polymorphism that collects the information for calling a method at runtime.
  • Super keyword can be used to access methods of the parent class from the child class.