Kamal Dua
Kamal Dua

Reputation: 11

Calling Non-Overidden Method from Child Class object

What I am not getting is that the money is picked from the Parent class but this pointer reference belongs to the Child Object? Both things should have belonged to one scope?

class Parent
{
    int money=10;
    Parent parentMethod(){
        System.out.println(money);
        return this;
    }
}
class Child extends Parent{
    int money=11;

}
public class Demo1 {
    public static void main(String[] args) {
        Child ch=new Child();
        System.out.println(ch.parentMethod());
        System.out.println(ch.parentMethod() instanceof Child);
    }
}

Output:

10
demos.Child@1540e19d
10
true

Upvotes: 1

Views: 66

Answers (1)

Eran
Eran

Reputation: 393936

Instance variables cannot be overridden. parentMethod() is defined in Parent class, so it only sees the money instance variables of Parent class.

If you had overridden parentMethod() in Child class, and accessed the money variable in the body of the Child class method, you would have seen the value of the Child class money instance variable.

Upvotes: 2

Related Questions