静态数据的初始化
如果数据属于某个基本类型,而且也没有对它进行初始化,那么它就会获得基本类型的标准初值;如果它是一个对象引用,那么除非心创建一个对象,并指派给该引用,否则它就是空值(null)
无论创建多少个对象,静态数据都只占用一份存储区域。
//4.4.2.1 public class StaticInitialization { public static void main(String[] args) { System.out.println("Creating new Cupboard() in main"); new Cupboard(); System.out.println("Creating new Cupboard() in main"); new Cupboard(); t2.f2(1); t3.f3(1); } static Table t2 = new Table(); static Cupboard t3 = new Cupboard(); } class Bow1 { Bow1(int marker) { System.out.println("Bow1(" + marker + ")"); } void f(int marker) { System.out.println("f(" + marker + ")"); } } class Table { static Bow1 b1 = new Bow1(1); Table() { System.out.println("Table()"); b2.f(1); } void f2(int marker) { System.out.println("f2(" + marker + ")"); } static Bow1 b2 = new Bow1(2); } class Cupboard { Bow1 b3 = new Bow1(3); static Bow1 b4 = new Bow1(4); Cupboard() { System.out.println("Cupboard()"); b4.f(2); } void f3(int marker) { System.out.println("f3(" + marker + ")"); } static Bow1 b5 = new Bow1(5); } |
输出结果:
Bow1(1)
Bow1(2)
Table()
f(1)
Bow1(4)
Bow1(5)
Bow1(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bow1(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bow1(3)
Cupboard()
f(2)
f2(1)
f3(1)
静态块
//4.4.2—think in java public class ExplicitStatic { public static void main(String[] args) { System.out.println("Inside main()"); Cups.c1.f(99); } } class Cup { Cup(int marker) { System.out.println("Cup(" + marker + ")"); } void f(int marker) { System.out.println("f(" + marker + ")"); } } class Cups { static Cup c1; static Cup c2; static { c1 = new Cup(1); c2 = new Cup(2); } Cups() { System.out.println("Cups()"); } } |
输出结果:
Inside main()
Cup(1)
Cup(2)
f(99)
public class Test { static int i = 1; static { i++; } public Test() { i++; } public static void main(String[] args) { Test t1 = new Test(); System.out.println(t1.i); //1 Test t2 = new Test(); System.out.println(t2.i); //2 } }
输出结果:
3
4
非静态实例初始化
public class Mugs { Mug c1; Mug c2; { c1 = new Mug(1); c2 = new Mug(2); System.out.println("c1 & c2 initialized"); } Mugs() { System.out.println("Mugs()"); } public static void main(String[] args) { System.out.println("Inside main()"); Mugs x = new Mugs(); } } class Mug { Mug(int marker) { System.out.println("Mug(" + marker + ")"); } void f(int marker) { System.out.println("f(" + marker + ")"); } } |
输出结果:
Inside main()
Mug(1)
Mug(2)
c1 & c2 initialized
Mugs()