this关键字作用
- 调用一个构造器(必须将构造器调用置于最起始处)
- 用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;
}
Flower(String s, int petals) {
this(petals);
//this(s); can't call two
this.s = s;
System.out.println("String & int args");
}
Flower() {
this("hi", 47);
System.out.println("defalut constructor (no args)");
}
void printPetalCount() {
//this.(11); Not inside non-constructor
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 args
defalut constructor (no args)
petalCount = 47s = hi
补充说明
- printPetalCount()方法说明,除构造器之外,编译器禁止在其他任何方法中调用构造器
- static方法中不能用this,static有点类似全局函数,属于类本身,而this指代当前对象