| Author |
a question regarding constructors' sequence
|
Li Wenfeng
Greenhorn
Joined: Aug 26, 2002
Posts: 22
|
|
Given the following code,what's the output? 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 { Bread b = new Bread(); Cheese c = new Cheese(); Lettuce l = new Lettuce(); Sandwich() { System.out.println("Sandwich()"); } public static void main(String[] args) { new Sandwich(); } } I think the output should be: Breed() Cheese() Lettuce() Meal() Lunch() PortableLunch() Sandwich() Actually, the result is: Meal() Lunch() PortableLunch() Breed() Cheese() Lettuce() Sandwich() Why are the three instance variables of Sandwich initialized between super() and the body of the constructor--Sandwich()?? thanks!!
|
SCJP2
|
 |
Dave Vick
Ranch Hand
Joined: May 10, 2001
Posts: 3244
|
|
Li Check out the JLS section 12.5 for the complete details on instance creation. Basically the order it happens in is this: -- execute any calls to another constructor (using this()) then do that constructor -- then execute either the explicit or implicit call to the super classes constructor -- then initialize all of the instance variables -- then the rest of the statements in the constructor. hope that helps
|
Dave
|
 |
 |
|
|
subject: a question regarding constructors' sequence
|
|
|