Polymorphism is a core concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It’s one of the four major OOP principles, alongside encapsulation, inheritance, and abstraction. Polymorphism in Java enables a single interface to be used for a general class of actions. The specific action is determined by the exact nature of the situation. There are two types of polymorphism in Java: compile-time (static) and runtime (dynamic) polymorphism.
Compile-Time Polymorphism
Compile-time polymorphism, also known as static polymorphism, is achieved through method overloading. Method overloading allows a class to have multiple methods with the same name but different parameters.
Example of Compile-Time Polymorphism:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Calculator { // Method to add two integers public int add(int a, int b) { return a + b; } // Overloaded method to add three integers public int add(int a, int b, int c) { return a + b + c; } } public class Test { public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println(calc.add(5, 10)); // Outputs 15 System.out.println(calc.add(5, 10, 15)); // Outputs 30 } } |
Runtime Polymorphism
Runtime polymorphism, or dynamic polymorphism, is achieved through method overriding. In method overriding, a subclass provides a specific implementation of a method already present in its superclass.
Example of Runtime Polymorphism:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class Animal { void speak() { System.out.println("The animal speaks"); } } class Dog extends Animal { // Overriding the speak method void speak() { System.out.println("The dog barks"); } } public class TestPolymorphism { public static void main(String[] args) { Animal myAnimal = new Animal(); // Create an Animal object myAnimal.speak(); // Outputs: The animal speaks Animal myDog = new Dog(); // Create a Dog object myDog.speak(); // Outputs: The dog barks } } |
Key Points about Polymorphism
- Flexibility and Scalability: Polymorphism offers flexibility and scalability to the code. It allows the extension of code without modifying the existing code.
- Use in APIs: It’s widely used in implementing interfaces and inheritance, making it fundamental for designing flexible and scalable APIs in Java.
- Enhances Code Reusability: Polymorphism enhances code reusability through the ability to use the same interface for different underlying forms of data types.
Conclusion
Polymorphism is a pivotal concept in Java and OOP, enabling objects of different classes to interact with each other through a common interface. By understanding and effectively using polymorphism, developers can write more flexible, scalable, and maintainable code. Whether through compile-time or runtime polymorphism, this OOP principle helps achieve a high level of abstraction and code reusability.