Polymorphism is a core concept in object-oriented programming that allows objects of different types to be treated as objects of a common superclass. In Java, it enables a single interface to represent multiple underlying forms or data types.
Runtime polymorphism occurs when a subclass overrides a method of its superclass. This allows the program to determine which method to call at runtime based on the actual object type.
class Animal {
void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("The dog barks");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("The cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.makeSound(); // Output: The dog barks
myCat.makeSound(); // Output: The cat meows
}
}
Compile-time polymorphism occurs when multiple methods in the same class have the same name but different parameters. The compiler determines which method to call based on the method signature.
public class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 10)); // Output: 15
System.out.println(calc.add(5.5, 10.5)); // Output: 16.0
}
}
@Override
annotation when overriding methodsTo fully understand and utilize polymorphism in Java, it's essential to be familiar with these related concepts:
Mastering polymorphism is crucial for writing flexible and maintainable Java code. It allows developers to create more abstract and modular designs, leading to more efficient and scalable applications.