日期:2014-05-20  浏览次数:20827 次

关于constructor的问题
代码如下:

public class Flower {
int petalCount = 0;
String s = "initial value";
Flower(int petals) {
petalCount = petals;
print("Constructor w/ int arg only, petalCount= "
+ petalCount);
}
Flower(String ss) {
print("Constructor w/ String arg only, s = " + ss);
s = ss;
}

Flower(String s, int petals) {
this(petals);
//! this(s); // Can’t call two!
this.s = s; // Another use of "this"
print("String & int args");
}
Flower() {
this("hi", 47);
print("default constructor (no args)");
}
void printPetalCount() {
//! this(11); // Not inside non-constructor!
print("petalCount = " + petalCount + " s = "+ s);
}
public static void main(String[] args) {
Flower x = new Flower();
x.printPetalCount();
}
}

运行结果:
Constructor w/ int arg only, petalCount= 47
String & int args
default constructor (no args)
petalCount = 47 s = hi

我想请问为什么string ss 的内容不显示出来? 是不是因为第一个constructor的参数已经设定成int的关系?
------解决方案--------------------
Flower x = new Flower();会调用你的默认构造函数

在你默认构造函数里面调用了含有两个参数的构造函数
Flower() {
this("hi", 47);
print("default constructor (no args)");
}
在含有两个参数的构造函数中只调用了参数为int型的构造函数,你的String ss没有调用到,所有不会有输出。
Flower(String s, int petals) {
this(petals);
//! this(s); // Can’t call two!
this.s = s; // Another use of "this"
print("String & int args");
}
------解决方案--------------------
public class Flower
{
int petalCount = 0;
String s = "initial value";

Flower(int petals)
{
petalCount = petals;
System.out.println("Constructor w/ int arg only, petalCount= "
+ petalCount);
}

Flower(String ss)
{
System.out.println("Constructor w/ String arg only, s = " + ss);
s = ss;
}

Flower(String s, int petals)
{
this(petals);     //第三步:由于petals变量是int类型的,所以调用构造方法Flower(int petals);
this.s = s; 
System.out.println("String & int args");
}

Flower()
{
this("hi", 47);     //第二步:由于是两个参数,调用Flower(String s, int petals);
System.out.println("default constructor (no args)");
}

void printPetalCount()
{
System.out.println("petalCount = " + petalCount + " s = " + s);
}

public static void main(String[] args)
{
Flower x = new Flower();     //第一步:调用无参数构造方法Flower();
x.printPetalCount();         //第四步:调用方法;
}
}