Reputation: 11
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
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