父类中的this

来源:互联网 发布:网络语红烧肉什么意思 编辑:程序博客网 时间:2024/05/29 03:39

      父类中的this到底指向的是父类还是子类?为此做了下实验,代码如下:

public class ThisInParent {
 
public ThisInParent() {
}
public static void main(String[] args) {
new Child();
new P();
}
}
class P {
public P() {
System.out.println(this.getClass().getName());
this.f();
}
 
public void f() {
System.out.println("parent");
}
}
 
class Child extends P {
public Child() {
 
}
 
public void f() {
System.out.println("child");
}
 
}

运行该类得到的结果如下:

Child
child
P
parent

从上述结果看出:
(1)new Child的过程中,作为Child的直接父类P因为子类的隐式调用也进行了构造器的调用,输出结果为类名Child和方法f()输出child,可以看出此时的this代表的是子类的引用,并且调用f()时调用的是子类重写的父类方法,更加证明了this为子类的引用。
(2)另外直接new P父类的过程中,直接输出了P,parent的结果。
所以由以上结论得出,具体new那一个对象,如果在其父类中有对this 的引用,则该this一律指向的的是该被new的子类。
下面有一个三层继承的例子,可以更好的加以佐证

public class ThisInParent {
 
public ThisInParent() {
}
 
public static void main(String[] args) {
new GrandChild();
new Child();
new P();
}
}
 
class P {
public P() {
System.out.println(this.getClass().getName());
this.f();
}
 
public void f() {
System.out.println("parent");
}
}
 
class Child extends P {
public Child() {
System.out.println(this.getClass().getName());
this.f();
}
 
public void f() {
System.out.println("child");
}
 
}
class GrandChild extends Child {
public GrandChild() {
}
public void f(){
System.out.println("grandChild");
}
}

输出结果:

GrandChild
grandChild
GrandChild
grandChild
Child
child
Child
child
P
parent


0 0