Appearance
Polymorphism
Polymorphism (having many forms) is the ability of an entity in an object-oriented model to refer to objects of different classes at different times. For example, a method that accepts an object of a certain class will also operate on its subclasses:
java
public class MyShapeCollection {
private List<Shape> shapes;
public MyShapeCollection() { shapes = new ArrayList<>(); }
public void add(Shape shape) { shapes.add(shape); }
public double getTotalArea() {
double total = 0;
for (Shape shape: shapes) {
total += shape.area();
}
}
}
We can pass any subclass of Shape
to the add
method:
java
MyShapeCollection myShapes = new MyShapeCollection();
myShapes.add(new Circle(2.0));
myShapes.add(new Rectangle(1.0, 3.0));
myShapes.add(new Rectangle(4.0, 2.0));
System.out.println(myShapes.getTotalArea());
We can store and iterate over any subclass of Shape
in the shapes
collection. When we invoke area()
on a shape
object, the polymorphic implementation of area()
is selected at runtime based on what the "actual" (instantiated) type of the shape
is (i.e., whether it is a Circle
or Rectangle
).