What is polymorphism, and how does one call site end up running different implementations?
Polymorphism is the ability to call one method and have different code run depending on the object that the call is really made on. The call site stays the same and the behaviour changes.
public class Main {
public static void main(String[] args) {
Animal[] animals = { new Dog(), new Cat(), new Bird() };
for (Animal a : animals) {
System.out.println(a.speak());
}
}
}
And here is the parent and the three children.
public class Animal {
public String speak() {
return "...";
}
}
public class Dog extends Animal {
@Override
public String speak() {
return "woof";
}
}
public class Cat extends Animal {
@Override
public String speak() {
return "meow";
}
}
public class Bird extends Animal {
@Override
public String speak() {
return "tweet";
}
}
So how does one call site end up running different implementations? The call site says a.speak() and the variable a is declared as an Animal. At runtime the variable holds a Dog, then a Cat, then a Bird, and the runtime looks at the actual object and runs the version of speak that belongs to it.
the loop runs the object the method that runs
----------------- ----------------- ------------------------
the first time a Dog Dog.speak
the second time a Cat Cat.speak
the third time a Bird Bird.speak
And this is called dynamic dispatch, and it is what makes the array work. The array holds three different kinds of thing and the loop does not check what any of them are.
And there is a second thing that polymorphism gives you, and it is about the calling side. The code that calls the method does not have to know the class of the object, so you can add a new kind of animal and the loop does not change at all. The new class is the only thing that has to be written.
And there is a third thing that is worth knowing about, and it is the rule that makes the whole thing work. The method that gets called is chosen by the actual object at runtime, and not by the type of the variable. That is why it is called runtime polymorphism. The type of the variable decides what the compiler lets you call, and the object decides what actually runs.
So the rule to remember is this. The variable gives the compiler the list of allowed methods, and the object decides which one runs.
The next two questions in this topic are about the practical value and about the limits.