OOP and design · Topic 5 of 12
Polymorphism
Definition​
Polymorphism means one call can run different code depending on the real object. You call a method on a parent type, and Java picks the child's version while the program runs.
Example code​
One loop, three different areas
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
private final double r;
Circle(double r) { this.r = r; }
double area() { return Math.PI * r * r; }
}
class Square extends Shape {
private final double side;
Square(double side) { this.side = side; }
double area() { return side * side; }
}
class Triangle extends Shape {
private final double base, height;
Triangle(double base, double height) { this.base = base; this.height = height; }
double area() { return 0.5 * base * height; }
}
class Demo {
public static void main(String[] args) {
Shape[] shapes = {new Circle(1), new Square(2), new Triangle(3, 4)};
for (Shape shape : shapes) {
// same call, the version that runs depends on the real object
System.out.printf("%s -> %.2f%n", shape.getClass().getSimpleName(), shape.area());
}
}
}
// Output:
// Circle -> 3.14
// Square -> 4.00
// Triangle -> 6.00
Finished this page? Track your progress (saved only in your browser).