Java: Instance Initialization

Instance Initialization is for initializing non-static variables for each object (while static for class). The blue block is executed before either one of the constructors, so it guarantees certain operations occur regardless of which constructor is called.
It seems very similar with Static Initialization except the static keyword. But note that, the Static Initialization is for class, you do not even need to create an object of that class, while Instance Initialization is for creating objects, it initializes variables for new objects, which can be used for Anonymous Inner Class. 

class Mug {
    public Mug(int marker) {
        System.out.println("Mug--->" + marker);
    }

    void print(int marker) {
        System.out.println("Print--->" + marker);
    }
}

 

class Mugs {
    Mug mug1;
    Mug mug2;
    {
        mug1 = new Mug(1);
        mug2 = new Mug(2);
        System.out.println("This is in Block Clause...");
    }

    // Initialized when used at the first time.
    static Mug mug3 = new Mug(3);

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

    public Mugs(int marker) {
        System.out.println("Mugs(int)...");
    }

    void print(int marker) {
        System.out.println("Print--->" + marker);
    }
}

 

public class Client {
        public static void main(String[] args) {
        System.out.println("Main...");
        // Note the output of the following statement.
        // The static mug3 in Mugs is first accessed to, then assigned to null.
        Mugs.mug3 = null;
        new Mugs();
        System.out.println("Main...");
        new Mugs(1);
    }
}

 

Result:

Main...
Mug--->3
Mug--->1
Mug--->2
This is in Block Clause...
Mugs()...
Main...
Mug--->1
Mug--->2
This is in Block Clause...
Mugs(int)...

 

 

From 《Thinking in Java》 4th Edition .p191

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值