2008/03/31

Java Constructor Invocation and Instance Variable Initialization

This is a tricky one:


abstract public class BasePayment {
public BasePayment(){
setFakeValue();
}
abstract public void setFakeValue();
}

public final class Payment extends BasePayment{
private String property = null;
public Payment(){
super();
System.out.println("after super(): " + this.getProperty());
}
public String getProperty() {
return property;
}
public void setFakeValue() {
System.out.println("Calling setFakeValue()");
this.property = "property";
System.out.println("After setFakeValue(), property: " + this.getProperty());
}

public static void main(String[] args) throws Exception{
Payment p = new Payment();
System.out.println("'new'ed a Payment, property value: " + p.getProperty());
}
}
What the println in the main() method will output? null? "property"?

It has something to do whether java will initialize the instance variable first, or will invoke the constructor of the super class first. The behaviour is fully documented (it better be!) at http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.8.7.1

And yes, the output is 'null'.

No comments:

Well well... why another J2EE blog? I benefited from other people's technical blogs, and guess what, it's a good idea to contribute some of my works too. Hope it's helpful and useful, to all of your folks.