注:参考了jit(java in thinking),示例都是那里面的。
1、在一个类中,this可以表示该类的当前实例;例如:
public class leaf {
private int i = 0;
leaf increment() {
i++;
return this;
}
void print() {
system.out.println("i = " + i);
}
public static void main(string[] args) {
leaf x = new leaf();
x.increment().increment().increment().print();
}
} ///:~
2、若为一个类写了多个构造器,那么经常都需要在一个构造器里调用另一个构造器,以避免写重复的代码。这时可以使用this,例如:
//: flower.java
// calling constructors with "this"
public class flower {
private int petalcount = 0;
private string s = new string("null");
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); // cant call two!
this.s = s; // another use of "this"
system.out.println("string & int args");
}
flower() {
this("hi", 47);
system.out.println(
"default constructor (no args)");
}
void print() {
//! this(11); // not inside non-constructor!
system.out.println(
"petalcount = " + petalcount + " s = "+ s);
}
public static void main(string[] args) {
flower x = new flower();
x.print();
}
} ///:~
而需要注意的是:在一个类a的内部类b中使用this它表示的并非是a.b的当前实例,而是a的当前实例;
