Polymorphism

AP Computer Science A· difficulty 4/5

public class Shape {
    public String name() { return "Shape"; }
}
public class Circle extends Shape {
    public String name() { return "Circle"; }
}
public class Square extends Shape {
    public String name() { return "Square"; }
}
// Usage:
ArrayList<Shape> list = new ArrayList<Shape>();
list.add(new Circle());
list.add(new Square());
list.add(new Shape());
String s = "";
for (int i = 0; i < list.size(); i++) {
    s += list.get(i).name();
}
System.out.print(s);

What is printed?

  • A

    ShapeShapeShape

  • B

    CircleSquare

  • C

    CircleSquareShape

    check_circle
  • D

    Compile error

Explanation

Each call uses dynamic dispatch on the actual stored object type, producing "CircleSquareShape".

Want 10 more like this — adaptive to your weak spots?

Related questions