Polymorphism in Java

πŸ“˜ Java πŸ‘ 39 views πŸ“… Dec 01, 2025
⏱ Estimated reading time: 2 min

Polymorphism is a key concept of object-oriented programming (OOP) in Java. The word polymorphism comes from Greek, meaning β€œmany forms.” It allows a single entity (method, object, or operator) to take multiple forms depending on the context. Polymorphism improves flexibility, maintainability, and reusability in Java programs.


1. Types of Polymorphism in Java

(a) Compile-Time Polymorphism (Method Overloading)

  • Also called static polymorphism.

  • Occurs at compile time.

  • Achieved by method overloading or operator overloading (Java supports method overloading only).

Example: Method Overloading

class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } } public class Test { public static void main(String[] args) { Calculator c = new Calculator(); System.out.println(c.add(5, 10)); // Calls int version System.out.println(c.add(5.5, 10.5)); // Calls double version } }

Key Points:

  • Same method name, different parameter lists.

  • Resolved at compile time.


(b) Run-Time Polymorphism (Method Overriding)

  • Also called dynamic polymorphism.

  • Occurs at runtime.

  • Achieved by method overriding, where a subclass provides a specific implementation of a method defined in the parent class.

Example: Method Overriding

class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } public class Test { public static void main(String[] args) { Animal a = new Dog(); a.sound(); // Calls overridden method in Dog } }

Key Points:

  • Method name and parameters remain the same.

  • Resolved at runtime based on the object type.


2. Advantages of Polymorphism

  • Code Reusability: Same method can work with different data types or objects.

  • Flexibility: Objects can be treated as instances of their superclass.

  • Maintainability: Reduces code duplication and simplifies updates.

  • Extensibility: New classes can be added with minimal changes to existing code.


3. Summary Table

TypeHow AchievedTimeExample
Compile-TimeMethod OverloadingCompileadd(int a, int b)
Run-TimeMethod OverridingRuntimeDog overrides Animal.sound

4. Conclusion

Polymorphism in Java allows a single interface or method to have multiple implementations, providing flexibility and improving the scalability of programs. Mastering polymorphism is essential for building robust and reusable Java applications.


πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes