一般情况下, this关键字指向的是当前对象的引用
在继承关系中,不管父类还是子类,这些类里面的this都代表了最终new出来时的那个类型的实例对象
this的指向也可以手动显示更改,下面看一个例子:
public class Test {
public static class Foo {
public class Bar{
public void func(){
System.out.println(this.getClass().getName()+this.hashCode()+"标记1");
//显示改变this指向为Foo
System.out.println(Foo.this.getClass().getName()+Foo.this.hashCode()+"标记2");
}
}
public void func(){
System.out.println(this.getClass().getName()+this.hashCode()+"标记3");
new Bar().func();
}
}
public static void main(String[] args) {
new Foo().func();
}
}
输出结果:
com.lxy.pojo.Test$Foo142257191标记3
com.lxy.pojo.Test$Foo$Bar1044036744标记1
com.lxy.pojo.Test$Foo142257191标记2
可以看到上面标记2处语句的this从指向Test$Fo$Bar变为了指向Test$Foo