this:返回当前对象(如下:this返回Flower)
注意点:this只能调用一个构造器,且构造器调用必须置于最起始处,否则会报错误
除构造器外其他任何地方禁止调用构造器,不然就会报错
public class Flower {
int petalCount=0;
String s = "initial value";
public Flower() {
this("hi",47);
System.out.println("无参构造");
}
public Flower( String s,int petalCount) {
this(petalCount);
//this(s); 一个this只能调用一个构造器,不然就会报错
this.s=s;
System.out.println("两个有参");
}
public Flower( String ss) {
this.s = ss;
System.out.println("ss");
}
public Flower(int ww) {
petalCount = ww;
System.out.println("int 构造 : petalCount="+petalCount);
}
void printaaa(){
//this(5); // 此处就会报错
System.out.println("aaa");
}
public static void main(String[] args) {
Flower f = new Flower();
}
}
输出:
int 构造 : petalCount=47
两个有参
无参构造