View on GitHub

我的学习笔记

好记性不如烂笔头

5.7 构造器初始化

返回
5.7.1 初始化顺序
5.7.2 静态数据初始化
5.7.3 显式的静态初始化
5.7.4 非静态实例初始化

5.7.1 初始化顺序

//:initialization/OrderOfInitialization.java

//When the constructor is coalled to create a
//Window object,you'll see a message
class Window{
    Window(int mark){ System.out.println("Windows("+mark+")");}
}

class House{
    Window w1=new Window(1);  //Before constructor

    House(){
        System.out.println("House()");
        w3=new Window(33);  //Reinitialize w3
    }

    Window w2=new Window(2); //After constructor
    void f(){System.out.println("f()");}
    Window w3=new Window(3); //At the end
}

public class OrderOfInitialization{
    public static void main(String[] args) {
        House h=new House();
        h.f();
    }
}/*OutPut:
Windows(1)
Windows(2)
Windows(3)
House()
Windows(33)
f()
 *///:~

5.7.2 静态数据初始化

5.7.3 显示的静态初始化

//:initialization/Spoon.java
public Spoon{
    static int i;
    static {    // static block (static sentences)
        i=11;
    }
}///:~
//: initialization/ExplicitStatic.java
class Cup{

    Cup(int marker){
        System.out.println("Cup("+marker+")");
    }
    void f_Cup(int marker){
         System.out.println("f_Cup("+marker+")");
    }
}

class Cups{
    static Cup cup1;
    static Cup cup2;
    static {    //The static initialization only run for one time
        cup1=new Cup(1);
        cup2=new Cup(2);
    }
    Cups(){
        System.out.println("Cups()");
    }
}

public class ExplicitStatic{
    public static void main(String[] args) {
        System.out.println("Inside main()");
        Cups.cup1.f_Cup(99);
    }
}/*Output: 
Inside main()
Cup(1)
Cup(2)
f_Cup(99)
*///:~

5.7.4 非静态实例初始化

//:initialization/Mugs.java
// Java "Instance initialization"
class Mug{
    Mug(int maker){
        System.out.println("Mug("+maker+")");
    }
    void f_Mug(int marker){
        System.out.println("f_Mug("+marker+")");
    }
}

public class Mugs{
    Mug mug1;
    Mug mug2;
    //this way of initialization is
    //necessarily for the initialize of anumouns inner-class
    {
        mug1=new Mug(1);
        mug2=new Mug(2);
        System.out.println("mug1 & mug2 initialized");
    }

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

    Mugs(int i){
        System.out.println("Mug(int)");
    }
    public static void main(String[] args) {
        System.out.println("Inside main()");
        new Mugs();
        System.out.println("new Mugs() completed");
        new Mugs();
        System.out.println("new Mugs() completed");
    }
}/*Output:
Inside main()
Mug(1)
Mug(2)
mug1 & mug2 initialized
Mugs()
new Mugs() completed
Mug(1)
Mug(2)
mug1 & mug2 initialized
Mugs()
new Mugs() completed
*///:~

返回