构造器初始化_02
来源:互联网 发布:丹尼格兰杰数据 编辑:程序博客网 时间:2024/06/05 08:39
无法阻止初始化的自动进行,它将在构造器被调用之前发生。
变量定义的先后顺序决定了初始化的顺序,即使变量定义散布于方法定义之间,它仍旧会在任何方法(包括构造器)之前得到初始化。
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
- 构造器初始化_02
- 构造函数初始化器
- 构造器初始化顺序
- 构造器初始化
- 构造器的初始化
- 构造函数初始化器
- Java 构造器初始化
- 构造器初始化
- 构造器确保初始化
- 构造函数初始化器
- 初始化与构造器
- 构造器的初始化
- 构造器初始化
- Android L Phone进程初始化_02
- 构造器与初始化块
- C# 构造函数初始化器
- 以构造器确保初始化
- 有多个构造器如何初始化
- 【户外知识】转:如何防止徒步穿越带来的运动伤害
- 野三坡-百里峡
- 敏捷开发之 12条敏捷原则
- 再好的代码没有电也跑不了
- RMAN深入解析之--BlockRecover恢复坏块
- 构造器初始化_02
- RMAN深入解析之--Incarnation应用(不完全恢复)
- AIX系统小错误之--Crontab故障
- Solaris 10下有趣的FTP错误--ROOT不能访问FTP
- 爬山为什么要穿登山鞋
- Unix系统性能监控工具之--SAR
- Oracle 学习之--Buffer Cache深入解析
- Oracle ASM错误之--ORA-15031、ORA-15014
- Oracle ASM错误之--ORA-15033