This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a question regarding constructors' sequence

 
Li Wenfeng
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!!
 
Dave Vick
Ranch Hand
Posts: 3244
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic