Polymorphism is a fundamental concept in object-oriented programming, and it refers to the ability of an object to take on many forms. In Java, polymorphism is implemented through two mechanisms: method overloading and method overriding.
Method overloading allows multiple methods with the same name to be defined in a class, as long as they have different parameter types. The compiler determines which method to call based on the arguments passed in.
Here’s an example:
public class Calculator {
public int add(int x, int y) {
return x + y;
}
public double add(double x, double y) {
return x + y;
}
}
In this example, we have two add
methods with different parameter types. We can call either method, depending on the types of arguments passed in.
Method overriding allows a subclass to provide its own implementation of a method that is already defined in its superclass. This allows a subclass to inherit the methods and fields of its superclass, but also to modify or extend its behavior as necessary.
Here’s an example:
public class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
In this example, the Cat
class extends the Animal
class and overrides its makeSound
method to provide its own implementation. We can call the makeSound
method on a Cat
object, and it will execute the Cat
implementation.
Polymorphism allows us to write more generic code that can work with objects of different types, without having to know their specific implementation details. It is a powerful tool for building flexible and extensible code in Java.