Polymorphism
Polymorphism lets one parent-typed variable refer to different subtype objects. Calling an overridden method uses the actual object's implementation.
This allows code to work against a stable abstraction instead of branching on every concrete type.
One type, different behavior
class Shape {
String draw() {
return "Shape draw";
}
}
class Circle extends Shape {
@Override
String draw() {
return "Circle draw";
}
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = {new Shape(), new Circle()};
for (Shape shape : shapes) {
System.out.println(shape.draw());
}
}
}
Output:
Shape draw
Circle draw
Both array slots have type Shape, yet the Circle object still prints its Circle-specific draw result.
A parent reference exposes only members declared by the parent type. Casting to reach subtype details should be rare and checked.
Store an Animal and a Cat in one array of Animal values, then call sound on each one.