shadowing is mostly when you have an instance variable x in the class, then in a method you declare a variable called x. So inside the method whenever you just use x, it will refer to the variable defined inside the method and not the instance variable. In order to access the instance variable you need to use the keyword this, as in this.x
No a subclass overriding an instance variable is like shadowing. But does refer to the variable type not the actual object type.
so Parent p = new Subclass();
When you refer to p.instance variable I believe you get the parent's instance variable value. But I could be wrong, because I always get confused on this point all the time myself.
Still confused! the returnIt() method will be choosed at runtime but as you can see this method return a shadowed variable x that it is defined in the superclass and the subclass too.
Result: the x returned by the method is defined in the subclass (object type not reference type!).
Joined: Aug 16, 2005
Instance variables cannot be overridden, ever. So the decision about which instance variable to access in any given situation is always based on reference type. Since the reference type for a is A, every time you access a.x no matter what the underlying object is, you will always get 5.
Methods on the other hand can be overridden, and resolution is made at runtime based on the underlying object type. Since a is actually pointing to an instance of B, it is B's returnIt() method that gets called, hence the result of 20.