Card 02/ 09
All 9 cards
ExampleDifficulty: Intermediate1 min
One Loop Over Three Shapes
Three classes that each draw themselves, and a loop that draws all of them without knowing what any of them is.
abstract class Shape { abstract void draw(); }
class Circle extends Shape { void draw() { System.out.println("circle"); } }
class Square extends Shape { void draw() { System.out.println("square"); } }
class Line extends Shape { void draw() { System.out.println("line"); } }List<Shape> shapes = List.of(new Circle(), new Square(), new Line());
for (Shape s : shapes) {
s.draw();
}circle
square
lineThe loop variable is declared Shape and the objects are three different classes. Line 4 runs a different body on every pass, and the loop contains no if, no type name and no test.
The list is typed List<Shape>, which is what makes the loop legal, and the objects inside it keep their real classes. The declared type decided what could be called; the actual object decided what ran.