当前位置: 技术问答>java相关
java中关于合成过程中初始化的一问
来源: 互联网 发布时间:2015-11-08
本文导语: 小第目前正在看TIJ2e看到第五章复用的时候有一个程序不理解,烦请各位给予帮助。程序如下: //: c06:Bath.java // Constructor initialization with composition. class Soap { private String s; Soap() { System.out.println("Soap()...
小第目前正在看TIJ2e看到第五章复用的时候有一个程序不理解,烦请各位给予帮助。程序如下:
//: c06:Bath.java
// Constructor initialization with composition.
class Soap {
private String s;
Soap() {
System.out.println("Soap()");
s = new String("Constructed");
}
public String toString() { return s; }
}
public class Bath {
private String
// Initializing at point of definition:
s1 = new String("Happy"),
s2 = "Happy",
s3, s4;
Soap castille;
int i;
float toy;
Bath() {
System.out.println("Inside Bath()");
s3 = new String("Joy");
i = 47;
toy = 3.14f;
castille = new Soap();
}
void print() {
// Delayed initialization:
if(s4 == null)
s4 = new String("Joy");
System.out.println("s1 = " + s1);
System.out.println("s2 = " + s2);
System.out.println("s3 = " + s3);
System.out.println("s4 = " + s4);
System.out.println("i = " + i);
System.out.println("toy = " + toy);
System.out.println("castille = " + castille);
}
public static void main(String[] args) {
Bath b = new Bath();
b.print();
}
} ///:~
执行结果如下:
Inside Bath()
Soap()
s1 = Happy
s2 = Happy
s3 = Joy
s4 = Joy
i = 47
toy = 3.14
castille = Constructed
我不理解的地方在于,new Bath()来产生b对象,而Bath的构造函数又产生了一个新的Soap对象,但是当b.print时,为什么没有返回castille对象的引用,而返回一个字串s,我们并没有调用castille的toString方法啊?这一章的前面好象有讲,但我没太看懂。
//bow
//: c06:Bath.java
// Constructor initialization with composition.
class Soap {
private String s;
Soap() {
System.out.println("Soap()");
s = new String("Constructed");
}
public String toString() { return s; }
}
public class Bath {
private String
// Initializing at point of definition:
s1 = new String("Happy"),
s2 = "Happy",
s3, s4;
Soap castille;
int i;
float toy;
Bath() {
System.out.println("Inside Bath()");
s3 = new String("Joy");
i = 47;
toy = 3.14f;
castille = new Soap();
}
void print() {
// Delayed initialization:
if(s4 == null)
s4 = new String("Joy");
System.out.println("s1 = " + s1);
System.out.println("s2 = " + s2);
System.out.println("s3 = " + s3);
System.out.println("s4 = " + s4);
System.out.println("i = " + i);
System.out.println("toy = " + toy);
System.out.println("castille = " + castille);
}
public static void main(String[] args) {
Bath b = new Bath();
b.print();
}
} ///:~
执行结果如下:
Inside Bath()
Soap()
s1 = Happy
s2 = Happy
s3 = Joy
s4 = Joy
i = 47
toy = 3.14
castille = Constructed
我不理解的地方在于,new Bath()来产生b对象,而Bath的构造函数又产生了一个新的Soap对象,但是当b.print时,为什么没有返回castille对象的引用,而返回一个字串s,我们并没有调用castille的toString方法啊?这一章的前面好象有讲,但我没太看懂。
//bow
|
任何对象都有toString()方法
因为这个方法是从Object类继承来的,你可以override它
object的实现就是一些和referrence有关的信息
因为这个方法是从Object类继承来的,你可以override它
object的实现就是一些和referrence有关的信息