Part 2 of 7 · 2 min read
One request, many answers
The receiver decides what happens.
Asking "what do you charge?" at a bakery, a taxi and a cinema gets three different answers, though the question is the same. The person asked decides how to answer.
GoF describes this. The operation that actually runs depends on two things: which request was made and which object received it. Different objects that support the same request may implement it in different ways. The run-time link between a request and the operation that fulfils it is dynamic binding. It means a request does not commit the program to one implementation until run time. The ability to swap objects that share an interface is polymorphism, and GoF calls it a key concept of object-oriented systems. It lets a client make few assumptions about other objects beyond the interface they support.
In Java, the pieces are: - A common type: an interface or a parent class. - Several classes that provide the method, each in its own way. A subclass that gives a new version of an inherited method overrides it. - A variable of the common type. At run time, Java picks the version that matches the actual object.
interface Shape {
double area();
}
class Circle implements Shape {
private final double radius;
Circle(double radius) { this.radius = radius; }
public double area() { return Math.PI * radius * radius; }
}
class Rectangle implements Shape {
private final double length, width;
Rectangle(double length, double width) { this.length = length; this.width = width; }
public double area() { return length * width; }
}
With Shape s = new Rectangle(3, 4); the call s.area() gives 12. With Shape s = new Circle(1); it gives 3.14159 (rounded). The calling line is the same, and the answer depends on the object.
Polymorphism
Polymorphism means that code written for a common type works with any object of that type, and each object answers in its own way.
Example: a loop over a list of Shape objects adds up area() and never asks which kind each one is.
Check yourself:
1. What decides which area() runs?
2. What is dynamic binding?
3. What does a client need to know about the objects it calls?