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
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));
}
}Shape constructor to set up the new object.Shape() has finished, so its variables are gone.Square() has finished, so its variables are gone.Shape constructor to set up the new object.Shape() has finished, so its variables are gone.Circle() has finished, so its variables are gone.total is created on the stack with the value 0.s is created on the stack and points to a new Square on the heap: {side: 2}.total. s goes out of scope and disappears.s is created on the stack and points to a new Circle on the heap: {r: 1}.total. s goes out of scope and disappears.for (Shape s : shapes).System.out.println("Total area: " + String.format("%.2f", total)).Total area: 7.14.Shape s = new Circle(1); s.area() runs?Answer: Circle.area(). Dynamic dispatch uses the object's class.
Answer: Makes the compiler check you are overriding. A typo in the name becomes a compile error.
← Inheritance and super · Abstract Classes →