public class Flower {
int petalCount = 0;
String s = "initial value";
Flower(int petals) {
petalCount = petals;
System.out.println("Constructor petalCount = " + petalCount);
}
Flower(String ss) {
System.out.println("Constructor s = " + ss);
s = ss;
}
Flower(String s, int petals) {
this(petals);
// this(s);
this.s = s;
}
Flower() {
this("hi", 47);
}
void printPetalCount() {
// this(11); 除构造器外,编辑器禁止在其他任何方法中调用构造器
System.out.println("s = " + s +"\n"+ "petalCount = " + petalCount);
}
public static void main(String[] args) {
Flower x = new Flower();
x.printPetalCount();
}
}
运行结果:
Constructor petalCount = 47
s = hi
petalCount = 47
构造器Flower(String s, int petals) 表明:尽管可以用this调用一个构造器,但却不能调用两个。此外,必须将构造器调用置于最起位置,否则编译器会报错。
网友评论