题目:
创建一个简单的类。在第二个类中,将一个引用定义为第一个类的对象。运用惰性初始化来实例化这个对象。
解答:
package seven;
class one {
String s;
public one(String s1) {
s = s1;
}
public String toString() {
return s;
}
public void setString(String snew) {
s = snew;
}
}
class second {
one One;
String s;
public second(String s1) {
s = s1;
}
public void check() {
if(One == null) {
System.out.println("NOT INITIALIZED");
} else {
System.out.println("INITIALIZED");
}
}
// Lazy Initlization
private one lazy() {
if(One == null) {
System.out.println("Create a One");
One = new one(s);
}
return One;
}
public one getOne() {
return lazy();
}
public String toString() {
return lazy().toString();
}
public void setOne(String sOne) {
lazy().setString(sOne);
}
}
public class exerciseOne {
public static void main(String[] args) {
second S = new second("STRING INITIALIZED");
S.check();
System.out.println(S.getOne());
S.check();
System.out.println(S);
S.setOne("NEW STRING");
System.out.println(S);
}
}
结果如下:
如果觉得不错,就用点赞或者关注或者留言,来代替五星好评吧~
谢谢各位~