Hi, I'm a bit confused on this topic, specially in shadowing variables.
output: 20 and 5 I know that method will be choosed at runtime(object type). but varaiables? All classes has a variable named x. The call of x depends on type or what?
Thank you.
SCWCD 1.4(Loading...), SCJP 1.4(98%), Bachelor of Engineering (computer science)
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.
Hi Adil, Well yes, method is chosen at runtime but variables are shadowed or hidden.
If A is the base class and B is a subclass of A and both have a variable named say x, then the variable accessed will depend on the Type of the object that accesses that variable.
Therefore, in your code, the variable x will be accessed from class A
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!).
Ryan Kade
Ranch Hand
Joined: Aug 16, 2005
Posts: 69
posted
0
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.