Monday, June 1, 2009

[note] java object initialize sequence


package wd;

class Foo {
String str;
Foo() {
System.out.println("foo");
}
Foo(String str) {
System.out.println("Foo." + str);
this.str = str;
}
public String toString() {
return str;
}
}

class Base {
Foo f1 = new Foo("1st");

static Foo sf1 = new Foo("sf 1st");

static{
System.out.println("Base.static");
sf1 = new Foo("static foo 1st changed");
sf2 = new Foo("static foo 2nd changed");
}
Foo f2 = new Foo("2nd");
Base() {
System.out.println("Base()");
}
Foo f3 = new Foo("3rd");

static Foo sf2 = new Foo("sf 2nd");
}

class Derived extends Base {
static {
System.out.println("Derived.static");
}

Derived() {
System.out.println("Derived()");
}
}

public class InitSequence {
public static void main(String[] args) {
new Derived();
System.out.println("d.sf1: " + Derived.sf1);
System.out.println("d.sf2: " + Derived.sf2);
}
}

No comments:

Post a Comment