Tools
Log in
English

Learn to codeJava

Java polymorphism

Based on Java 17instanceof · Java 16+

Java polymorphism: one area() call, three shapes, no if-instanceof chains.

In one line

When you handle many objects through one parent type (here Shape), calling the same method runs the version that fits each real object.

Why you need it

If you split the area code with if (circle) ... else if (rectangle) ..., every new shape means hunting down that if and editing it. Miss one place and the area comes out as 0 (mistake 1 below).

Promise area() in Shape and let each shape fill it in. The total method that adds the areas never changes, however many shape types you add.

Everyday picture

Think of the play button on a remote. Press it with a TV and you get a picture; press it with a speaker and you get only sound. The person pressing does not need to know what is inside. area() is the play button; circle, rectangle and triangle are different devices.

Example code

Main.java · 70 lines
import java.util.List; interface Shape {    double area();     default String label() {        return getClass().getSimpleName();    }} class Circle implements Shape {    private final double r;     Circle(double r) {        this.r = r;    }     @Override    public double area() {        return Math.PI * r * r;    }} class Rect implements Shape {    private final double w;    private final double h;     Rect(double w, double h) {        this.w = w;        this.h = h;    }     @Override    public double area() {        return w * h;    }} class Triangle implements Shape {    private final double base;    private final double height;     Triangle(double base, double height) {        this.base = base;        this.height = height;    }     @Override    public double area() {        return base * height / 2;    }} public class Main {    static double total(List<Shape> shapes) {        double sum = 0;        for (Shape s : shapes) {            double a = s.area();            System.out.println(s.label() + " " + String.format("%.2f", a));            sum += a;        }        return sum;    }     public static void main(String[] args) {        List<Shape> shapes = List.of(new Circle(1.5), new Rect(3, 4), new Triangle(6, 2));        double sum = total(shapes);        System.out.println("Total " + String.format("%.2f", sum));    }}

When to use it

  • Several kinds share one action name (pay with any payment method, send through any channel, area of any shape)
  • More kinds are likely to come later. You will only add classes.
  • The same switch or instanceof chain shows up in several places

Same name with different parameters is overloading, not overriding. Polymorphism happens with overridden methods.

Interface default methods (label) need Java 8+, and instanceof Circle c, which declares the variable right away, needs Java 16+.

Common mistakes

Branching on type with instanceof

A triangle was added but nobody updated this if chain, so its area comes out as 0.0. Let each shape compute its own area() and keep the caller to one line.

Wrong

class AreaCalc {    static double area(Shape s) {        if (s instanceof Circle) {            Circle c = (Circle) s;            return Math.PI * c.r * c.r;        } else if (s instanceof Rect) {            Rect r = (Rect) s;            return r.w * r.h;        }        return 0;    }}

When you run it0.0

Fixed

class AreaCalc {    static double area(Shape s) {        return s.area();    }}

When you run it6.0

Changing the parameters and calling it an override

Same name but different parameters means a new method (overloading), not an override. The area() that Shape promised is still missing, so javac stops you.

Wrong

class Square implements Shape {    double side = 2;     public double area(double scale) {        return side * side * scale;    }}

What javac sayserror: Square is not abstract and does not override abstract method area() in Shape

Fixed

class Square implements Shape {    double side = 2;     @Override    public double area() {        return side * side;    }}

Casting down without checking

Casting a Shape to (Circle) without looking throws an exception at run time. instanceof Circle c checks and declares the variable in one go (Java 16+).

Wrong

public class Main {    public static void main(String[] args) {        Shape s = new Rect();        Circle c = (Circle) s;        System.out.println(c.r);    }}

When you run itException in thread "main" java.lang.ClassCastException: class Rect cannot be cast to class Circle

Fixed

public class Main {    public static void main(String[] args) {        Shape s = new Rect();        if (s instanceof Circle c) {            System.out.println(c.r);        } else {            System.out.println("not a circle: " + s.area());        }    }}

When you run itnot a circle: 12.0

Check yourself

Question 1

Using the example classes, what does this print?

public class Main {    public static void main(String[] args) {        Shape s = new Rect(2, 5);        System.out.println(s.label() + " " + s.area());    }}

Show the answer

Answer: 2. Rect 10.0 label() returns the real class name, Rect. area() returns a double, so it prints 10.0, not 10.

Question 2

You add a Hexagon that implements Shape. What must change in total?

Show the answer

Answer: 2. Nothing in total changes As long as Hexagon has its own area(), total just calls s.area() and keeps working. That is the point of polymorphism.

Questions people ask

Is polymorphism the same as overloading?

No. Polymorphism picks an overridden method at run time by looking at the object. Overloading picks between same-named methods with different parameters at compile time.

Can a parent-type variable call child methods?

Only methods declared in the parent type. If you need a child-only method, check with instanceof first.

Is using instanceof wrong?

No. But when the same instanceof chain repeats in several places, moving that behavior into overridden methods is easier to maintain.