Polymorphism in Java (Static and Dynamic)

โšก Smart Summary

Polymorphism in Java allows one interface to represent many forms, so a single method name behaves differently across related classes. It is a pillar of object-oriented design that promotes flexibility, code reuse, and clean extension of legacy banking, medical, and enterprise systems.

  • ๐ŸŽญ Many forms, one name: Polymorphism in Java lets the same method name dispatch to different implementations based on the actual object type at execution time.
  • ๐Ÿ”€ Two flavors: Compile-time polymorphism uses Method Overloading, while runtime polymorphism uses Method Overriding through inheritance and the JVM.
  • โ›“๏ธ Static vs Dynamic binding: Overloaded calls resolve at compile time through Static binding, while overridden calls resolve at runtime through Dynamic binding.
  • โœ… Super keyword power: The super keyword lets a subclass invoke the parent implementation before adding its own specialized behavior on top.
  • ๐Ÿงช Real-world reach: Banking accounts, hospital staff hierarchies, and shape rendering engines all rely on polymorphism to grow new requirements without breaking tested code.

Polymorphism in Java

What is Polymorphism in Java?

Polymorphism in Java occurs when one or more classes or objects are 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. The goal is communication, while the approach may differ.

For example, a smartphone is used for communication. The communication mode can be a call, a text message, a picture message, or an email. The goal is common, that is communication, but the approach is different. This behavior is the essence of Polymorphism. Now we will learn Polymorphism in Java with example code, diagrams, and step-by-step explanations.

Click here if the video is not accessible

Why Use Polymorphism in Java?

Polymorphism in Java is used because it makes code flexible, reusable, and easier to maintain. A single reference variable of a parent type can point to several child objects, so the same call adapts to whichever subclass is supplied. This pattern keeps tested code untouched while new behavior is added through specialized subclasses, which is exactly why frameworks such as Spring and Jakarta EE depend on it.

Java Polymorphism in OOPs with Example

Consider one parent class named Account with functions for deposit and withdraw. The Account class has two child classes. The operation of deposit and withdraw is the same for Saving and Checking accounts, so the inherited methods from the 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 common in the software industry. Functionality for a privileged Banking Account with Overdraft Facility must be added. Overdraft is a facility where a customer can withdraw an amount greater than the available balance in the account. The withdraw method for the privileged account needs a fresh implementation, while the tested code in Savings and Checking accounts is left untouched. That isolation is the advantage of OOPS.

Java Polymorphism

Step 1) When the withdraw method for the Saving account is called, the method defined in the parent Account class is executed.

Java Polymorphism

Step 2) When the withdraw method for the privileged account (overdraft facility) is called, the withdraw method defined in the privileged class is executed. This dispatch is Polymorphism in OOPs.

Java Polymorphism

Method Overriding in Java

Method Overriding is the process of redefining a superclass method inside a subclass. The subclass keeps the same contract, but supplies a fresh implementation that is selected when the program runs.

Rules for Method Overriding

  • The method signature, that is the method name, parameter list, and return type, has to match exactly.
  • The overridden method can widen the accessibility, but it cannot narrow it. If the method is private in the base class, the child class can make it public but not the other way around.

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 Method Overloading and Method Overriding

Method Overloading happens inside the same class with the same method name but different signatures. Method Overriding happens across a parent-child class relationship, where the subclass redefines a method declared in the superclass.

Method Overloading
Method Overriding
Method Overloading is in the same class, where more than one method has the same name but different signatures. Method Overriding is when one of the methods in the superclass is redefined in the subclass. 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 the same name and signature in the superclass and the subclass. The call to an overridden method is resolved at runtime through Dynamic binding inside the JVM.

Dynamic Polymorphism Example

A reference variable of the superclass can refer to a subclass 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 diagram of Polymorphism.

The call obj.treatPatient() will execute the treatPatient() method of the subclass Surgeon. When a base class reference is used to call a method, the method that is invoked is decided by the JVM based on the actual object the reference is pointing to. Even though obj is a reference to Doctor, it calls the method of Surgeon, because it points to a Surgeon object. The decision is made during runtime, which is why it is termed Dynamic Polymorphism or runtime polymorphism.

Difference Between Static and Dynamic Polymorphism

Static Polymorphism in Java is a type of polymorphism that collects the information for calling a method at compilation time, while 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, the name is static.

Ex:

void sum (int a , int b);
void sum (float a, double b);
int sum (int a, int b); //compiler gives error.
When a reference variable is calling an overridden method, the method to be invoked is determined by the object the reference variable is pointing to. This can only be determined at runtime when the code is under execution, which is why the name is 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 the Doctor class and then perform its own specific behavior? In this case the keyword super can 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 method of the superclass inside the subclass. Next, we will learn about the super keyword, Inheritance, and Polymorphism in Java with example programs.

Example: To learn Inheritance, Polymorphism, and the 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(){
            // overridden 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, and run the code. Observe the output.

Step 3) Uncomment lines 6 to 9. Save, compile, and run the code. Observe the output.

Step 4) Uncomment line 10. Save and compile the code.

Step 5) Error = ? This is because the subclass cannot access private members of the superclass.

FAQs

Polymorphism in Java is the ability of an object to take many forms. The same method name can run different code depending on which subclass object is referenced at runtime, which is the core OOP behavior.

Java supports compile-time polymorphism through Method Overloading and runtime polymorphism through Method Overriding. Overloading resolves at compile time via Static binding, while Overriding resolves at runtime via Dynamic binding handled by the JVM.

Static binding links a method call to its definition at compile time and is used for Method Overloading. Dynamic binding links the call at runtime based on the actual object type and powers Method Overriding in Java.

The super keyword lets a subclass call the overridden method or access a data member from its parent class. This allows the child to reuse the parent logic and then layer specialized behavior on top of it.

AI tutors such as ChatGPT and GitHub Copilot Chat can explain Polymorphism in Java with custom analogies, generate practice problems, walk through inheritance trees, and quiz learners on Static binding versus Dynamic binding for faster mastery.

Yes. AI-driven refactoring assistants like Cursor, Sourcegraph Cody, and IntelliJ AI Assistant can spot duplicated conditionals, propose class hierarchies, and rewrite legacy Java code so that Method Overriding replaces repeated if-else chains.

Summarize this post with: