package c04;/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2007/7/16
 * Time: 下午 09:43:15
 * To change this template use File | Settings | File Templates.
 */
class Bowl{
    Bowl(int er) {
        System.out.println("Bowl(" + er + ")");
    }    void f(int er) {
        System.out.println("f(" + er + ")");
    }
}
class Table{
    static Bowl b1 = new Bowl(1);    Table() {
        System.out.println("Table()");
        b2.f(1);
    }    void f2(int er) {
        System.out.println("f2(" + er + ")");
    }
    static Bowl b2 = new Bowl(2);
}class Cupboard{
    Bowl b3 = new Bowl(3);
    static Bowl b4 = new Bowl(4);    Cupboard() {
        System.out.println("Cupboard()");
        b4.f(2);
    }    void f3(int er) {
        System.out.println("f3(" + er + ")");
    }    static Bowl b5 = new Bowl(5);
}public class StaticInitialization {
    public static void main(String[] args) {
        System.out.println("Creating new Cupboard() in main");
        new Cupboard();
        System.out.println("Creating new Cupboard() in main");
        new Cupboard();
        t2.f2(1);
        t3.f3(1);    }    static Table t2 = new Table();
    static Cupboard t3 = new Cupboard();
}打印的結果如下::Bowl(1)
Bowl(2)
Table()
f(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
f2(1)
f3(1)_________________________________
為甚麼
static Table t2 = new Table();
 static Cupboard t3 = new Cupboard();
沒有產生對象,或者說打印出相應的數據...

解决方案 »

  1.   

    ???你确定?
    Bowl(1)
    Bowl(2)
    Table()
    f(1)
    这不就是static Table t2 = new Table();的结果么???
      

  2.   

    你要是愿意,把下面的这个程序运行一遍看看.
    public class Z extends X{static{ //静态代码块
    System.out.println("我是子类的静态代码块,除了父类静态代码块和静态属性(类变量)我是最先执行的");
    }
    static C c= new C(); //静态属性Y2 y=new Y2();{ System.out.println("我是子类初始化块,我的优先级和非静态属性一样,我们之间的顺序以代码顺序为准"); } //初始化块
    Z(){System.out.println("我是子类构造函数");}public static void main(String[] args){
    new Z();
    }
    }
    class X{static{System.out.println("我是父类的静态代码块,我是最先执行的"); } //静态代码块static C2 c= new C2(); //静态属性{ System.out.println("我是父类初始化块,我的优先级和非静态属性一样,我们之间的顺序以代码顺序为准"); } //初始化块
    Y b=new Y(); //非静态属性X(){System.out.println("我是父类构造函数");}
    }
    class Y{
    Y(){System.out.println("我是父类非静态属性,和具体的类实例相关,我可能在初始化块前执行也可能在其后");}
    }class Y2{
    Y2(){System.out.println("我是子类非静态属性,和具体的类实例相关,我可能在初始化块前执行也可能在其后");}
    }class C{
    C(){System.out.println("我是子类的一个静态属性(类变量),我和之前的初始化过程都是针对类的,与实例无关");}
    }class C2{
    C2(){System.out.println("我是父类一个静态属性(类变量),我比子类的静态代码块执行的还早");}
    }