This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
You're confusing yourself by using the variable x in two places. Change the names of the two variables and it will make more sense.
Using a more defined method name, rather than a generic get might make it easier to follow as well.
Variables don't get overridden, they get 'shadowed.' It's the shadowing that is causing confusion.
Look at the following code. From Java's point of view, there is no difference. Why would you expect the getZero method in this code to return anything other than 0? (Assuming it compiles. I didn't compile it.)
So, you have a class Cast which extends class Tree. Now in line 6 you create a new Cast object, and in line 7 you call the get() method on that object. In line 13 you access the variable x of the object via the 'this' reference.
Note that there is only one object - the object to which 'c' refers. The 'this' reference in line 13 refers to the same object that 'c' refers to in lines 6 and 7.
Jesper Young wrote:The 'this' reference in line 13 refers to the same object that 'c' refers to in lines 6 and 7.
So why does it print 0 instead of 10? The visible x is that contains the value of 10. The x from tree is hidden.
Hidden doesn't mean that it is not accessible -- as you have seen with this example. Your get() method uses the "hidden" x variable -- as the first responder to this topic mentioned, "instance variables do not take part in polymorphism".
Ninad Kulkarni wrote:
Here the nearest scope of x is tree class not cast class. Java choose always nearest scope. Correct me if I am wrong.
This is not a case of two variables being in scope, and java choosing the one that is "nearest scope" (quotes because it is not an official term).
The x variable (of the cast class) is *not* in scope to the get() method. Period. To prove this, you can move the other x variable "really far away", and you will see, that it will not access the x variable in the cast class.