Polymorphism
A reference of a supertype can point at an object of any subtype. The call through that reference runs the method of the object, not the method of the type of the variable, and that choice is made at run time. The feature is called dynamic dispatch, and it is what a collection of shapes needs.
Dynamic dispatch
The array below has the type Shape[] and holds a circle and a rectangle. The loop calls name() and area() through the supertype, and each object answers with its own override.
The file Shapes.java:
public class Shapes {
public static void main(String[] args) {
Shape[] shapes = {new Circle(2), new Rectangle(3, 4)};
for (Shape shape : shapes) {
System.out.println(shape.name() + ": " + shape.area());
}
Shape shape = shapes[0];
if (shape instanceof Circle circle) {
System.out.println("radius: " + circle.radius());
}
}
}
class Shape {
String name() {
return "shape";
}
double area() {
return 0;
}
}
class Circle extends Shape {
private final double radius;
Circle(double radius) {
this.radius = radius;
}
double radius() {
return radius;
}
@Override
String name() {
return "circle";
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private final double width;
private final double height;
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
String name() {
return "rectangle";
}
@Override
double area() {
return width * height;
}
}
javac -Xlint:all Shapes.java
java Shapes
circle: 12.566370614359172
rectangle: 12.0
radius: 2.0
The area of the circle is pi * 2 * 2 and the area of the rectangle is 3 * 4; the loop did not know which was which. The three lines come from one array, one loop and two overrides, which is the shape of most object-oriented code.
A supertype reference
A circle can be assigned to a Shape variable because a circle is a shape. That widening assignment is called an upcast and needs no cast. The variable can call only the methods of Shape, so shape.radius() would not compile even when the object is a circle.
The method that runs is the override of the object, which is why area() gives the circle formula. Java makes that choice at run time, from the class of the object, and a variable that changes its object changes the answer on the next call.
instanceof
instanceof asks whether an object is of a given type, and the pattern form declares a variable of that type in the same expression. Inside the if body the variable is already cast, so no second cast and no separate check is needed.
The check is a run-time one: it is false for a null reference and true for an object of the type or of a subtype. It is the tool for the case where a supertype list holds different objects and one operation exists on only some of them; the pattern switch of lesson 060 replaces a long chain of these checks.
A cast that fails
A cast from the supertype to a subtype is checked at run time. When the object is not of that type, the JVM throws ClassCastException, and the program can catch it or let it end the thread.
public class Casting {
public static void main(String[] args) {
Shape shape = new Circle(1);
if (shape instanceof Rectangle rectangle) {
System.out.println("rectangle: " + rectangle.area());
} else {
System.out.println("not a rectangle");
}
try {
Rectangle bad = (Rectangle) shape;
System.out.println(bad.area());
} catch (ClassCastException error) {
System.out.println("caught: " + error.getMessage());
}
}
}
class Shape {
double area() {
return 0;
}
}
class Circle extends Shape {
private final double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private final double width;
private final double height;
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
double area() {
return width * height;
}
}
javac -Xlint:all Casting.java
java Casting
not a rectangle
caught: class Circle cannot be cast to class Rectangle (Circle and Rectangle are in unnamed module of loader 'app')
The pattern check answers false and the cast throws, which is the difference between asking and assuming. The message names both classes, so a log with this line is enough to see which object arrived where a rectangle was expected.
Exercises
- Add a Triangle to Shapes.java and its area.
- Add a method name() and instanceof.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does dynamic dispatch choose?
Answer
The override of the object the reference points at
The JVM looks at the class of the object at the call, not at the type of the reference.
-
What can a
Shapevariable do with a circle object?Answer
Call the methods of Shape, which run the circle overrides
The variable sees the supertype interface; the methods it calls are dispatched to the object.
-
What does
instanceofreturn for a null reference?Answer
false
There is no object, so there is no type to match.
-
What does this program print?
public class Q1 { public static void main(String[] args) { Shape shape = new Circle(); System.out.println(shape.area()); } } class Shape { double area() { return 1; } } class Circle extends Shape { @Override double area() { return 2; } }Answer
2.0
The object is a circle, so the circle override runs through the shape reference.
-
What does this program print?
public class Q2 { public static void main(String[] args) { Shape[] shapes = {new Circle(), new Square()}; int total = 0; for (Shape shape : shapes) { total += shape.sides(); } System.out.println(total); } } class Shape { int sides() { return 0; } } class Circle extends Shape { @Override int sides() { return 1; } } class Square extends Shape { @Override int sides() { return 4; } }Answer
5
The circle gives 1 and the square 4, and the loop adds both.
-
What does this program print?
public class Q3 { public static void main(String[] args) { Shape shape = new Circle(); if (shape instanceof Square) { System.out.println("square"); } else { System.out.println("other"); } } } class Shape { } class Circle extends Shape { } class Square extends Shape { }Answer
other
The object is a circle, so the test for a square is false.
-
What does this program print?
public class Q4 { public static void main(String[] args) { Shape shape = new Circle(); try { Square square = (Square) shape; System.out.println("ok"); } catch (ClassCastException error) { System.out.println("caught"); } } } class Shape { } class Circle extends Shape { } class Square extends Shape { }Answer
caught
The object is not a square, so the cast throws and the catch prints.
-
What does this program print?
public class Q5 { public static void main(String[] args) { Shape shape = new Circle(); if (shape instanceof Circle circle) { System.out.println("circle"); } } } class Shape { } class Circle extends Shape { }Answer
circle
The pattern matches, the variable is bound, and the body prints.
-
Why is an upcast, such as assigning a Circle to a Shape, allowed without a cast?
Answer
Every circle is a shape, so the assignment cannot fail
The subtype relation guarantees the object has every member the supertype declares.
-
What does a downcast check at run time?
Answer
That the object really is of the target type
The cast succeeds only for an object of that type or a subtype, and otherwise throws ClassCastException.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev