Skip to content
Justice Tech School

Polymorphism

A parent type variable can hold any child. The overridden method of the real object runs.

Example
public class Main {
  interface Shape { double area(); }
  record Circle(double r) implements Shape { public double area() { return Math.round(Math.PI * r * r * 100) / 100.0; } }
  record Sq(double s) implements Shape { public double area() { return s * s; } }
  public static void main(String[] args) {
    Shape[] s = { new Circle(1), new Sq(2) };
    for (Shape x : s) System.out.println(x.area());
  }
}

Result

3.14
4.0

Exercise

Parent holds child.

Shape s = new ();

Quiz Test

Which method runs?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.