Sunday, February 21, 2010

Java Constructors

What does the following code print?
 1 package cspuzzles;
 2 
 3 class SuperSuperClass {
 4     public SuperSuperClass(){
 5         System.out.println("SuperSuperClass constructor");
 6     }
 7 
 8     public SuperSuperClass(String s){
 9         System.out.println("SuperSuperClass constructor: " + s);
10     }
11 }
12 
13 class SuperClass extends SuperSuperClass {
14     public SuperClass(){
15         System.out.println("SuperClass constructor");
16     }
17 
18     public SuperClass(String s){
19         this();
20         System.out.println("SuperClass constructor: " + s);
21     }
22 }
23 
24 public class Post001 extends SuperClass{
25     public Post001(){
26         super("Message from Post001");
27     }
28 
29     public static void main(String[] args) {
30         new Post001();
31     }
32 }
33 
It prints:
SuperSuperClass constructor
SuperClass constructor
SuperClass constructor: Message from Post001

We have a hierarchy of objects. The bottom of the hierarchy is the class Post001. Class Post001 is a subtype of SuperClass and SuperClass is a subtype of SuperSuperClass. When, a class is instantiated, for each of its superclasses at least one constructor is executed. In this example, the two constructors in SuperClass are executed but only one constructor in SuperSuperClass is executed. Let's follow the calls:
  1. Line 30: instantiates an object Post001, therefore executing the constructor of Post001.
  2. Line 26: the constructor of Post001 explicitly calls a constructor of its superclass using the keyword super. It calls the constructor version that receives a string.
  3. Line 19: the constructor calls the overloaded constructor that receives no parameters using this().
  4. Line 15: in fact, before line 15 is executed, an implicit call super() is executed resulting in a call to the no-argument constructor in SuperSuperClass.
  5. Line 5: this is the first print statement executed. To be more precise, before line 5 is executed, a call to super() is made (i.e. a call to the constructor in class Object)
  6. After this, the stack of constructor calls is returned until the program is finished.
What other tips about java constructor do you know? Let's hear about them in the comments.

See you next puzzle!

No comments:

Post a Comment