← Java from Scratch Lesson 40 of 88 · 10 XP

Polymorphism

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A subclass overrides a method of its parent. Which version gets called is decided by the object's real type, not by the variable's type:

class Shape {
    double area() { return 0; }

    @Override
    public String toString() { return getClass().getSimpleName() + String.format(" %.2f", area()); }
}

class Circle extends Shape {
    double r;
    Circle(double r) { this.r = r; }

    @Override
    double area() { return Math.PI * r * r; }
}

Shape s = new Circle(1);
s.area();      // 3.14… — the Circle version was called

@Override isn't required, but it asks the compiler to check: a typo in the name (aera()) becomes an error instead of a new method.

Under the hood. In Java all instance methods are "virtual" by default (in C++ and C# you need the word virtual). The JVM keeps a method table for each class and calls through it.

Task. Finish Circle(r), Square(a), Triangle(a, h) (the area is a·h/2). The program prints each shape and the total of the areas.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.