Polymorphism
Polymorphism allows objects to be treated as instances of their parent class rather than their actual class. It provides a way to perform a single action in different forms.
Types of Polymorphism
There are two types of polymorphism in Java:
- Compile-time Polymorphism (Method Overloading)
- Runtime Polymorphism (Method Overriding)
Method Overloading
Method overloading allows a class to have more than one method with the same name, differentiated by parameters:
public class MathOperations {
// 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 static void main(String[] args) {
MathOperations math = new MathOperations();
System.out.println(math.add(10, 20)); // Outputs: 30
System.out.println(math.add(10, 20, 30)); // Outputs: 60
}
}
Method Overriding
Method overriding allows a subclass to provide a specific implementation of a method already provided by its superclass:
public class Animal {
public void makeSound() {
System.out.println("Animal sound");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
public static void main(String[] args) {
Animal myCat = new Cat();
myCat.makeSound(); // Outputs: Meow
}
}
In this example, the Cat
class overrides the makeSound
method of the Animal
class.
Continue exploring our intermediate tutorials to learn more about Java programming.