Java对象引用的初始化方式:
(1) 在定义对象的位置;
(2) 在类的构造器中;
(3) 在使用对象之前, 即惰性初始化;
(4) 实例初始化.
代码
-
/**
-
* 四种初始化方式
-
* <p/>
-
* Created by wang on 15/8/5.
-
*/
-
class Soap {
-
public Soap() {
-
System.out.println("Soap");
-
}
-
-
@Override
-
public String toString() {
-
return "Constructed";
-
}
-
}
-
-
public class TestInit {
-
private String s1 = "Happy"; // 定义初始化
-
private Soap s2;
-
private String s3, s4;
-
-
// 实例初始化
-
{
-
s2 = new Soap();
-
}
-
-
public TestInit() {
-
s3 = "Good"; // 构造器初始化
-
}
-
-
@Override
-
public String toString() {
-
s4 = "Girl"; // 惰性初始化
-
return "TestInit{" + "s1='" + s1 + ", s2=" + s2 +
-
", s3='" + s3 + ", s4='" + s4 + '}';
-
}
-
-
public static void main(String[] args) {
-
TestInit ti = new TestInit();
-
System.out.println(ti);
-
}
-
}
-
/*
-
Output:
-
Soap
-
TestInit{s1='Happy, s2=Constructed, s3='Good, s4='Girl}
-
*/
阅读(2937) | 评论(0) | 转发(0) |