Polymorphism is the concept that you can access objects of different types through the same interface.
<aside>
💡 To know whether an object is polymorphic, you can perform a simple test. If the object successfully passes multiple is-a or instanceof
tests, it’s polymorphic.
</aside>
Static Polymorphism is when the compiler can determine the executed "version".This is also mentioned as Compile-Time polymorphism, Static binding, Compile-Time binding, Early binding and Method overloading.
For instance, you can implement multiple methods within the same class that use the same name, but uses a different set of parameters. This is called method overloading and represents a static form of polymorphism. The parameters set have to differ in at least one of the following three criteria:
Due to the different sets of parameters, each method has a different signature. That signature allows the compiler to identify which method to call and binds it to the method call.
class Calculator {
void add(int a, int b) {
System.out.println(a+b);
}
void add(int a, int b, int c) {
System.out.println(a+b+c);
}
}
public class StaticPolymorphism {
public static void main(String args[]) {
Calculator calculator = new Calculator();
// method with 2 parameters is called
calculator.add(10, 20); //output: 30
// method with 3 parameters is called
calculator.add(10, 20, 30); //output: 60
}
}
Dynamic Polymorphism is when the compiler can't determine the executed "version" and the difference exists only at runtime. This is also mentioned as Run-Time polymorphism, Dynamic binding, Run-Time binding, Late binding and Method overriding.
Lets assume there are methods with same method signature in classes in a class hierarchy (parent-child relationships), these methods are in different forms (this is known as method overriding). Then when an object is assigned to a class reference and when a method of the object is called, the method in the object’s class is executed. Not the method of the reference class (if the reference is a parent class). 🤪 Let's see an example:
class Animal {
public void speak(){
System.out.println("mmmmm");
}
}
class Dog extends Animal {
public void speak() {
System.out.println("Woof");
}
}
class Duck extends Animal {
public void speak() {
System.out.println("Quack");
}
}
class Cat extends Animal {
public void speak() {
System.out.println("Meow");
}
}
public class DynamicPolymorphism {
public static void main(String args[]) {
Animal parentAnimal = new Animal(); // Animal reference and object
Animal dog = new Dog(); // Animal reference, Dog object
Animal duck = new Duck(); // Animal reference, Duck object
Cat cat = new Cat(); // Cat reference and objject
parentAnimal.speak(); // Output: "mmmmm"
dog.speak(); // Output: "Woof"
duck.speak(); // Output: "Quack"
cat.speak(); // Output: "Meow"
}
}