构造器初始化_02

无法阻止初始化的自动进行,它将在构造器被调用之前发生。

变量定义的先后顺序决定了初始化的顺序,即使变量定义散布于方法定义之间,它仍旧会在任何方法(包括构造器)之前得到初始化。

import static net.mindview.util.Print.*;

// When the constructor is called to create a
// Window object, you'll see a message:
class Window {
  Window(int marker) { print("Window(" + marker + ")"); }
}

class House {
  Window w1 = new Window(1); // Before constructor
  House() {
    // Show that we're in the constructor:
    print("House()");
    w3 = new Window(33); // Reinitialize w3
  }
  Window w2 = new Window(2); // After constructor
  void f() { print("f()"); }
  Window w3 = new Window(3); // At end
}

public class OrderOfInitialization {
  public static void main(String[] args) {
    House h = new House();
    h.f(); // Shows that construction is done
  }
} /* Output:
Window(1)
Window(2)
Window(3)
House()
Window(33)
f()

可见初始化操作是在第一位的。

静态数据的初始化,看下面这段代码

import static thinkinginjava.Print.*;

class Go {
    static String s1 = "run";
    static String s2, s3;
    static {                               //静态块或静态句子(首先被执行,且只执行了一次,注意看输出) No.1
        s2 = "drive car";
        s3 = "fly plane";
        print("s2 & s3 initialized");
    }
    static void how() {
        print(s1 + " or " + s2 + " or " + s3);
    }
    Go() { print("Go()"); }    
}

public class ExplicitStaticEx {
    public static void main(String[] args) {
        print("Inside main()");  //No.4
        Go.how();//No.5
        print("Go.s1: " + Go.s1);//No.6        
    }
    static Go g1 = new Go(); // No.2
    static Go g2 = new Go();//No.3
}
//output:

s2 & s3 initialized
Go()
Go()
Inside main()
run or drive car or fly plane
Go.s1: run

如果main方法外的初始化操作不是静态的,即没有static,那么这两句话不会被执行。加上static之后,他们会先于main方法执行,且只会被初始化一次。

构造器可以看作是static方法。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值