4.4 成员初始化
局部变量在使用之前必须初始化。
package com.sunny.hello.c4; public class Test { void f() { int i; //i++; 编译错误,因为i未初始化 } }
但是,若将基本类型设为一个类的数据成员,情况则会变得稍微有些不同。由于任何方法都可以初始化或使用那个数据,所以在正式使用前,若还是强迫程序员将其初始化为一个适当的值,就可能不是一种实际的做法。然而,若为其赋予一个垃圾值,同样
是非常不安全的。因此,一个类的所有基本类型数据成员都会保证获得一个初始值。
package com.sunny.hello.c4; public class InitialValues { public static void main(String[] args) { Measurement d = new Measurement(); d.print(); } } class Measurement { boolean t; char c; byte b; short s; int i; long l; float f; double d; void print() { System.out.println("Data type Inital value\n" + "boolean " + t + "\n" + "char " + (int)c + " \n" + "byte " + b + "\n" + "short " + s + " \n" + "int " + i + "\n" + "long " + l + " \n" + "float " + f + " \n" + "double " + d + "\n"); } }
运行结果:
Data type Inital value boolean false char 0 byte 0 short 0 int 0 long 0 float 0.0 double 0.0
4.4.1 规定初始化
class Measurement { boolean b = true; char c = 'x'; byte B = 47; short s = 60; int i = 999; long l = 1; float f = 3.14f; double d = 3.14159; Depth o = new Depth(); // ... } class Depth { }
4.4.2 构建器初始化
1.初始化顺序
package com.sunny.hello.c4; public class OrderOfInitialization { public static void main(String[] args) { Card t = new Card(); t.f(); } } class Tag { Tag(int marker) { System.out.println("Tag(" + marker + ")"); } } class Card { Tag t1 = new Tag(1); Card() { System.out.println("Card()"); t1 = new Tag(33); } Tag t2 = new Tag(2); void f() { System.out.println("f()"); } Tag t3 = new Tag(3); }
运行结果:
Tag(1) Tag(2) Tag(3) Card() Tag(33) f()
在执行Card这个类的构造函数之前,会对Card类中所有的成员变量进行初始化。
package com.sunny.hello.c4; 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 Bow { Bow(int marker) { System.out.println("Bow(" + marker + ")"); } void f(int marker) { System.out.println("f(" + marker + ")"); } } class Table { static Bow b1 = new Bow(1); Table() { System.out.println("Table()"); b1.f(1); } void f2(int marker) { System.out.println("f2(" + marker + ")"); } static Bow b2 = new Bow(2); } class Cupboard { Bow b3 = new Bow(3); static Bow b4 = new Bow(4); Cupboard() { System.out.println("Cupboard()"); b4.f(2); } void f3(int marker) { System.out.println("f3(" + marker + ")"); } static Bow b5 = new Bow(5); }
运行结果:
Bow(1) Bow(2) Table() f(1) Bow(4) Bow(5) Bow(3) Cupboard() f(2) Creating new Cupboard() in main Bow(3) Cupboard() f(2) Creating new Cupboard() in main Bow(3) Cupboard() f(2) f2(1) f3(1)
4.5 数组初始化
4.5.1 多维数组
4.6 总结