Why is "this" from superclass calling method from subclass?

Viewed 71

I'm running over this problem while working with the following inheritance and 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? Am I being confused with something here? Thank you for spending time.

1 Answers

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.

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.

Note: constructors are not overriden, ever. So calling this(params) will not delegate to subclass.

Related