this关键字代码演示
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;
}
/**
* 尽管可以用this调用一个构造器,但却不能调用两个。此外,必须将构造器调用于最起始处,否则编译器会报错。
* @param s
* @param petals
*/
Flower(String s, int petals) {
this(petals);
this.s = s;
System.out.println("String & int arg");
}
/**
* 默认无参构造器
*/
Flower() {
this("hi", 47);
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();
x.printPetalCount();
}
}
代码输出
Constructor w/ int arg only,petalCount = 47
String & int arg
default constructor (no args)
petalCount = 47 s = hi