Polymorphism and Overriding

One call, s.area(), runs different code for a Square and a Circle. Java picks the method from the real object, at run time.

Java · beginner · 8 min · 22 steps · free

What you'll learn

PolymorphismDemo.java

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

class Square extends Shape {
    double side;
    Square(double side) { this.side = side; }

    @Override
    double area() {
        return side * side;
    }
}

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

    @Override
    double area() {
        return 3.14 * r * r;
    }
}

public class PolymorphismDemo {
    public static void main(String[] args) {
        Shape[] shapes = {new Square(2), new Circle(1)};
        double total = 0;
        for (Shape s : shapes) {
            total += s.area();
        }
        System.out.println("Total area: " + String.format("%.2f", total));
    }
}

Step by step

  1. An array of Shape holding a Square and a Circle.
  2. Java runs the Shape constructor to set up the new object.
  3. Shape() has finished, so its variables are gone.
  4. Square() has finished, so its variables are gone.
  5. An array of Shape holding a Square and a Circle.
  6. Java runs the Shape constructor to set up the new object.
  7. Shape() has finished, so its variables are gone.
  8. Circle() has finished, so its variables are gone.
  9. An array of Shape holding a Square and a Circle.
  10. total is created on the stack with the value 0.
  11. s is created on the stack and points to a new Square on the heap: {side: 2}.
  12. s is declared as Shape, but the object is a Square, so Square's area() runs.
  13. 2 × 2 = 4.
  14. The value it returned, 4, is stored in total. s goes out of scope and disappears.
  15. s is created on the stack and points to a new Circle on the heap: {r: 1}.
  16. Same line, a Circle this time.
  17. 3.14 × 1 × 1 = 3.14.
  18. The value it returned, 7.140000000000001, is stored in total. s goes out of scope and disappears.
  19. Java moves to the next element of the loop: for (Shape s : shapes).
  20. Line runs: System.out.println("Total area: " + String.format("%.2f", total)).
  21. It prints Total area: 7.14.
  22. Total area 7.14. One line of code worked for every kind of shape: that is polymorphism.

Common mistakes

Best practices

Key takeaways

Check yourself

Shape s = new Circle(1); s.area() runs?

Answer: Circle.area(). Dynamic dispatch uses the object's class.

What does @Override do?

Answer: Makes the compiler check you are overriding. A typo in the name becomes a compile error.

·

More in Object-Oriented Programming