What is polymorphism, and how do you write code that works with different implementations without knowing them in advance?
Polymorphism means that one piece of code can work with several different kinds of thing, as long as they all agree on the same set of methods. You write against the shared shape and the runtime gives you the right behaviour.
public class Main {
public static void main(String[] args) {
java.util.List<Shape> shapes = new java.util.ArrayList<>();
shapes.add(new Circle(2.0));
shapes.add(new Rectangle(3.0, 4.0));
shapes.add(new Square(5.0));
for (Shape shape : shapes) {
System.out.println(shape.area());
}
}
}
And the key is the type of the variable. The variable shape is declared as a Shape, so the calling code only knows the methods that Shape declares. But the object at runtime is a Circle or a Rectangle, and the area method that runs is the one from that class.
public interface Shape {
double area();
}
And there are two ways that Java lets you do this, and it is worth knowing the difference.
the way how it works the limit
------------------- --------------------------------- -------------
overriding the subclass has its own version the type must
of the method be there at
compile time
interfaces the behaviour comes from the the object has
interface to be the
interface type
And there is a third thing that this style buys you, and it is the important one. The loop at the bottom does not know how many kinds of shape there are. When somebody adds a Triangle next month, the loop does not change at all. The new class implements the interface, and the code that was already working keeps working.
the class the change needed in the loop
------------------------- ---------------------------------
Circle none
Rectangle none
Square none
Triangle, added later none
So the rule to remember is this. Write against the shared shape, and let the runtime pick the behaviour.
The next two questions in this topic look at the plain meaning and at the risk of adding a new subclass.