Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon.
There are two types of polymorphism:-
- Method Polymorphism through overloading.
- Object polymorphism by inheritance / interfaces.
Polymorphism in Java can be implemented through method overriding and interfaces. Here are the two main ways to achieve polymorphism in Java:
- Method Overriding (Runtime Polymorphism):
- Inheritance is used to achieve method overriding.
- Subclasses provide a specific implementation for a method that is already defined in its superclass.
- The method in the subclass must have the same signature (name, return type, and parameters) as the method in the superclass.
- The actual method that gets executed is determined at runtime based on the type of object.
Example:
javaclass Animal {
void makeSound() {
System.out.println("Some generic sound");
}
}class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
}class Cat extends Animal {
void makeSound() {
System.out.println("Meow");
}
}public class PolymorphismExample {
public static void main(String[] args) {
Animal a;
a = new Dog();
a.makeSound(); // Output: Barka = new Cat();
a.makeSound(); // Output: Meow
}
}
- Interfaces (Compile-time Polymorphism):
- Interfaces in Java allow you to define a contract that multiple classes can implement.
- Different classes can provide different implementations for the methods declared in the interface.
- Objects of these classes can be referred to by the interface type, and the appropriate method implementation is invoked at compile-time.
Example:
javainterface Animal {
void makeSound();
}class Dog implements Animal {
public void makeSound() {
System.out.println("Bark");
}
}class Cat implements Animal {
public void makeSound() {
System.out.println("Meow");
}
}public class PolymorphismExample {
public static void main(String[] args) {
Animal a;
a = new Dog();
a.makeSound(); // Output: Barka = new Cat();
a.makeSound(); // Output: Meow
}
}
Both method overriding and interfaces contribute to achieving polymorphism in Java, allowing for flexibility and code reusability. The choice between them depends on the specific requirements and design of your application.