简体   繁体   English

为什么超类中的“this”会从子类中调用方法?

[英]Why is “this” from superclass calling method from subclass?

I'm running over this problem while working with the following inheritance and JDK 14我在使用以下 inheritance 和 JDK 14 时遇到了这个问题

interface A {

    default void a() {
        System.out.println("default a");
    }

    default void b() {
        System.out.println("default b");
    }
    
}

class AImp implements A {

    @Override
    public void a() {
        System.out.println("a from AImp");
    }

    @Override
    public void b() {
        System.out.println("b from AImp");
        this.a();
    }

}

class B extends AImp {

    @Override
    public void a() {
        System.out.println("a from B");
    }

    @Override
    public void b() {
        System.out.println("b from B");
        super.b();
    }

}

when I run当我跑步时

B b = new B();
    
b.b();

console gives控制台给出

b from B
b from AImp
a from B

How come the keyword this in the AImp is referencing the instance of class B? AImp中的this关键字怎么会引用 class B 的实例? Am I being confused with something here?我对这里的东西感到困惑吗? Thank you for spending time.谢谢你花时间。

You have created an instance of B , it is it's dynamic type and due to dynamic binding always the method declared in B is called, because it overrides from A.您已经创建了B的一个实例,它是动态类型,并且由于动态绑定,总是调用 B 中声明的方法,因为它从 A 覆盖。

It does not matter from where you call the method, but it matters, what is the dynamic type.哪里调用方法并不重要,重要的是动态类型是什么。

With super.method() it is different, it explicitly goes up in the inheritance.super.method()不同的是,它在 inheritance 中显式上升。

Note: constructors are not overriden, ever.注意:构造函数永远不会被覆盖。 So calling this(params) will not delegate to subclass.所以调用this(params)不会委托给子类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM