Polymorphism is the ability of a single object to take on multiple forms. In Java, polymorphism is implemented using inheritance, method overloading, and method overriding.
Here is an example of polymorphism using method overloading:
public class Calculator {
public int add(int x, int y) {
return x + y;
}
public int add(int x, int y, int z) {
return x + y + z;
}
}
Calculator calc = new Calculator();
int sum1 = calc.add(1, 2); // sum1 is 3
int sum2 = calc.add(1, 2, 3); // sum2 is 6
In this example, the Calculator class has two versions of the add method: one that takes two arguments and one that takes three arguments. Both of these methods have the same name, but they have different parameter lists, so they are considered to be overloaded versions of the same method.
Here is an example of polymorphism using method overriding:
public class Animal {
public void makeSound() {
System.out.println("Some generic animal sound");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
Animal animal = new Dog();
animal.makeSound(); // prints "Woof!"
In this example, the Animal class has a makeSound method that prints a generic animal sound. The Dog class extends the Animal class and overrides the makeSound method to provide a specific implementation for dogs. When the makeSound method is called on a Dog object, the version defined in the Dog class will be used, rather than the version defined in the Animal class.
Top comments (0)