Construction order of a subclass with composed parts

In the Java program below, SmartPhone inherits from Phone, which inherits from Device, and each phone class also creates a part object in a field initialiser.


Java
class Screen  { Screen()  { System.out.println("Screen"); } }
class Battery { Battery() { System.out.println("Battery"); } }
class Device  { Device()  { System.out.println("Device"); } }

class Phone extends Device {
    private Screen screen = new Screen();
    Phone() { System.out.println("Phone"); }
}

class SmartPhone extends Phone {
    private Battery battery = new Battery();
    SmartPhone() { System.out.println("SmartPhone"); }
}


The statement new SmartPhone(); runs once. Arrange the five printed lines in the order they appear on the console, first line first.

Loading ordering steps…

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Composition, Inheritance Questions: