Polymorphism is the power of a single object to tackle a number of kinds. In Java, polymorphism is carried out utilizing inheritance, technique overloading, and technique overriding.
Right here is an instance of polymorphism utilizing technique 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
On this instance, the Calculator class has two variations of the add technique: one which takes two arguments and one which takes three arguments. Each of those strategies have the identical identify, however they’ve totally different parameter lists, so they’re thought-about to be overloaded variations of the identical technique.
Right here is an instance of polymorphism utilizing technique overriding:
public class Animal {
public void makeSound() {
System.out.println("Some generic animal sound");
}
}
public class Canine extends Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
Animal animal = new Canine();
animal.makeSound(); // prints "Woof!"
On this instance, the Animal class has a makeSound technique that prints a generic animal sound. The Canine class extends the Animal class and overrides the makeSound technique to supply a selected implementation for canine. When the makeSound technique is named on a Canine object, the model outlined within the Canine class shall be used, reasonably than the model outlined within the Animal class.