Saad Bin Iqbal
Saad Bin Iqbal

Reputation: 65

Why "THIS" keyword denotes Child object into Parent class's method?

I'm using Child and Parent relationship using Inheritance. I had written a code where I use 'THIS' keyword in a method of Parent class and the same method is overridden in my Child class. When I call Parent class method from Child class overridden method using 'Super' keyword then in Parent class method, the 'THIS' keyword denotes Child object class, and when I call a method from Parent class method using 'THIS' keyword then It call Child class method(this method is same and also available in Parent & Child Class using overriding).

    class Parent {

    void onResume() {
        println("Parent:OnResume" + this) // Here 'this' denotes Child class's Object

        this.show() // here Child class's method is invoked
        show()      // here Child class's method is invoked as well
    }

    void show() {
        println("Parent:Show")
    }

}

class Child extends Parent {

    override 
    void onResume() {
        super.onResume()
        println("Child:->OnResume" + this)
    }

    override 
    void show() {
        println("Child:Show")
    }

}

//Calling code
Parent parentRef = new Child()
parentRef.onResume()

If I create an Object of Child class using Parent class reference variable like

Parent parentRef = new Child()

then 'this' denotes Child object in onResume() method of Parent class and when we call show() method in Parent then it call Child class's show() method.

Please let me clear why it happens so. As I know 'this' refers Current object of the class so here why 'this' refers Child object from Parent class. Please provide deep and internal details for this reason. Thanks in advance.

Upvotes: 0

Views: 1773

Answers (2)

Mark Jeronimus
Mark Jeronimus

Reputation: 9543

When you override a method, you overwrite the functionality of the overridden method.... unless the child class calls super.show() from somewhere. In other words, the child is in full control of whether the original (overridden) functionality is still available or not and from where it is available. (The child is not limited to calling super.show() from within the overridden show() but may call it from other methods and constructors as well!)

Upvotes: 0

Eran
Eran

Reputation: 393841

this references the current instance. If you create an instance of Child, the runtime type of this is Child, regardless of whether you write this in the parent class code or the child class code.

And if you call this.someMethod() in the Parent class code, if someMethod is overridden by Child class, the Child class method will be executed.

Upvotes: 7

Related Questions