Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 773
Ngọc Hy Avatar asked Sep 06 '26 07:09

Ngọc Hy


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.

like image 131
Hawk Avatar answered Sep 07 '26 21:09

Hawk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!