this.a = a;
}
public void print() {
print();
System.out.println("Hello from B!");
}
}
运行结果:
Hello from A!
Hello from B!
在这个例子中,对象 A 的构造函数中,用 new B(this)把对象 A 自己作为参数传递
给了对象 B 的构造函数。
3. 注意匿名类和内部类中的中的 this。
有时候,我们会用到一些内部类和匿名类。当在匿名类中用 this 时,这个 this 则指
的是匿名类或内部类本身。这时如果我们要使用外部类的方法和变量的话,则应该加上外
部类的类名。如下面这个例子:
public class A {
int i = 1;
public A() {
Thread thread = new Thread() {
public void run() {
for(;;) {
A.this.run();
try {
sleep(1000);
} catch(InterruptedException ie) {
}
}
}
};
thread.start();
}
public void run() {
System.out.println("i = " + i);
i++;
}
public static void main(String[] args) throws Exception {
new A();
}
}