Question : Order of constructor calls

Duplicating Objects using a Constructor
 Hi,

I was running following example

 Order of constructor calls
 
 
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
class Meal {
  Meal() {
    System.out.println("Meal()");
  }
}

class Bread {
  Bread() {
    System.out.println("Bread()");
  }
}

class Cheese {
  Cheese() {
    System.out.println("Cheese()");
  }
}

class Lettuce {
  Lettuce() {
    System.out.println("Lettuce()");
  }
}

class Lunch extends Meal {
  Lunch() {
    System.out.println("Lunch()");
  }
}

class PortableLunch extends Lunch {
  PortableLunch() {
    System.out.println("PortableLunch()");
  }
}

class Sandwich extends PortableLunch {
  private Bread b = new Bread();

  private Cheese c = new Cheese();

  private Lettuce l = new Lettuce();

  public Sandwich() {
    System.out.println("Sandwich()");
  }
}

public class class10 {
  public static void main(String[] args) {
    new Sandwich();
  }
} 
 

getting output like

Meal()
Lunch()
PortableLunch()
Bread()
Cheese()
Lettuce()
Sandwich()

 I was not sure why output has Bread Cheese, Lettuse.

I was not clear on the output, flow of execution, concept behind the program. Any ideas, links, suggestions, resources, sample code highly appreciated. Thanks in advance

Answer : Order of constructor calls

whenever a constructor is called, the parent classes constructor needs to be called (first)

Random Solutions  
 
programming4us programming4us