Polymorphism in Java is the ability of an object to take on multiple forms. In object-oriented programming, polymorphism allows objects of different classes to be treated as if they are objects of the same class, making code more flexible and reusable.
There are two types of polymorphism in Java:
- Compile-time polymorphism (Method Overloading)
- Runtime polymorphism (Method Overriding)
Compile-time polymorphism (Method Overloading)
Compile-time polymorphism, also known as method overloading, occurs when a class has multiple methods with the same name but different parameters. The compiler chooses the correct method to call based on the number, types, and order of the arguments passed to the method. Here’s an example:
public class Calculator { public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; } } public class Main { public static void main(String[] args) { Calculator calculator = new Calculator(); int sum1 = calculator.add(2, 3); double sum2 = calculator.add(2.5, 3.5); System.out.println("Sum of integers: " + sum1); System.out.println("Sum of doubles: " + sum2); } }
In the above example, the Calculator
class has two add()
methods with the same name but different parameter types. The Main
class creates an instance of the Calculator
class and calls both the add()
methods with different arguments, which outputs:
Sum of integers: 5 Sum of doubles: 6.0
Runtime polymorphism (Method Overriding)
Runtime polymorphism, also known as method overriding, occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. When a method is called on an object of the subclass, the subclass’s method is called, rather than the superclass’s method. Here’s an example:
class Animal { public void makeSound() { System.out.println("The animal makes a sound"); } } class Dog extends Animal { public void makeSound() { System.out.println("The dog barks"); } } public class Main { public static void main(String[] args) { Animal animal1 = new Animal(); Animal animal2 = new Dog(); animal1.makeSound(); animal2.makeSound(); } }
In the above example, the Animal
class has a makeSound()
method that outputs “The animal makes a sound”. The Dog
class extends the Animal
class and overrides the makeSound()
method to output “The dog barks”. The Main
class creates an instance of the Animal
class and an instance of the Dog
class, and calls the makeSound()
method on both objects. The output is:
The animal makes a sound The dog barks
The makeSound()
method is polymorphic because it takes different forms depending on the object that calls it. When the method is called on the Animal
object, the Animal
class’s implementation is used, and when the method is called on the Dog
object, the Dog
class’s implementation is used.