This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes a question regarding constructors' sequence Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "a question regarding constructors Watch "a question regarding constructors New topic
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
 
jQuery in Action, 2nd edition
 
subject: a question regarding constructors' sequence
 
Similar Threads
What should I have for Lunch?
Proper Diet
java programing homework help!
JavaFx XML file read
Help me to select the menu!