public class Think
{
private int petalCount = 0;
private String s = new String("null");
Think(int petals)
{
petalCount = petals;
System.out.println(
"Constructor w/ int arg only, petalCount= "
+ petalCount);
}
Think(String ss)
{
System.out.println(
"Constructor w/ String arg only, s=" + ss);
s = ss;
}
Think(String s, int petals)
{
this(petals);
this.s = s;
System.out.println("String & int args");
}
Think()
{
this("hi", 47);
System.out.println(
"default constructor (no args)");
}
void print()
{
System.out.println(
"petalCount = " + petalCount + " s = "+ s);
}
public static void main(String[] args) {
Think x = new Think();
x.print();
}
}
谁能和说下这个实现的过程~~~~
----------------解决方案--------------------------------------------------------
因为我觉得只能打出 0=0 null=null;
不过结果不是这样~~~结果是:
Constructor w/ int arg only, petalCount= 47
String & int args
default constructor (no args)
petalCount = 47 s = hi
为什么啊?
----------------解决方案--------------------------------------------------------
Think x = new Think();
调用构造函数Think(),运行到this("hi", 47);调用构造函数Think(String s, int petals)。再运行到this(petals);调用构造函数Think(int petals).其中不需要再调用其他构造函数了,运行其中的代码,然后按照刚才的次序倒着回去。最后调用print()方法输出。
我的理解,不对的地方请指教
----------------解决方案--------------------------------------------------------
这样理解是对的!
那是不是THIS这个就相当于调用呢?
----------------解决方案--------------------------------------------------------
这里this就是调用构造函数用的
感觉和super调用父类的构造函数一样
但是我看的core java上说两者有不同,没搞太明白,继续研究
----------------解决方案--------------------------------------------------------