Java中静态数据的初始化顺序
Java的类中的数据成员中包含有静态成员(static)时,静态数据成员的初始化顺序是怎样的呢?
【程序实例1】
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class Bowl { Bowl(int marker) { System.out.println("Bowl("+marker+")"); } void f1(int marker) { System.out.println("f1("+marker+")"); } } class Table { static Bowl bowl1=new Bowl(1); Table() { System.out.println("Table()"); bowl2.f1(1); } void f2(int marker){ System.out.println("f2("+marker+")"); } static Bowl bowl2=new Bowl(2); } class Cupboard { Bowl bowl3=new Bowl(3); static Bowl bowl4=new Bowl(4); Cupboard() { System.out.println("Cupboard()"); bowl4.f1(2); } void f3(int marker) { System.out.println("f3("+marker+")"); } static Bowl bowl5=new Bowl(5); } class Ideone { public static void main (String[] args) //throws java.lang.Exception { System.out.println("Creating new Cupboard() in main"); new Cupboard(); System.out.println("Creating new Cupboard() in main"); new Cupboard(); table.f2(1); cupboard.f3(1); } static Table table=new Table(); static Cupboard cupboard=new Cupboard(); }
【运行结果】
Bowl(1) Bowl(2) Table() f1(1) Bowl(4) Bowl(5) Bowl(3) Cupboard() f1(2) Creating new Cupboard() in main Bowl(3) Cupboard() f1(2) Creating new Cupboard() in main Bowl(3) Cupboard() f1(2) f2(1) f3(1)
从上面的执行结果可以看出:
在初始化变量时,Java中static数据成员初始化优先于局部变量,先按定义的顺序初始化静态变量,然后是局部变量,最后执行类的构造函数。
作者: Acode
出处: http://www.cnblogs.com/acode/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接 如有问题, 可留言咨询.