what does return this do in this code?

In this code

class Parent {

    void show() {
        System.out.print("parent");
    }

    Parent a() {
        return this;
    }

}

class Child extends Parent {

    void show() {
        System.out.print("child");
    }

    public static void main(String arg[]) {
        Parent a = new Child();
        Parent b = a.a();
        b.show();
    }
}

What does return this; do? b.show() is invoking the child method show. So does this return reference to its child class? If not then how is the show() method of child being called?


Solution 1:

First of all, all non private and non static methods in Java are virtual, which means that you will always execute the method of the type of the object reference.

In this case, you have

parent a=new child();

which means the client (the class/method) using a can only execute the methods defined in parent class but the behavior is defined by type child.

After this, when you execute:

parent b=a.a();

a.a() will return this, but a is a child and this is the current object reference, which is a. Value of b is a.

Then you execute

b.show();

Which is invoking child#show, so the program will output "child".