Variables can't be overridden. They can be shadowed or hidden.
If you have a method it is possible to alter that method in a subclass: that is overriding. If you have a field and declare a local variable with the same name, that local variable shadows the field and hides it. See the Java Language Specification page 86. The original field remains unchanged, however, and can be found with the this. syntax. If you have a superclass variable and a subclass variable with the same name the subclass variable hides the superclass variable. There is a little example here in the JLS. Note that in that example the hiding and hidden variables are of different type, whereas overridden methods must have the same signature and just about the same return types and Exception declarations.
well!!Mr Campbell i saw the example it is shown that the variables of super class are hidden by sublass by changing the data type but what will happen if the variable name and the data type of variable in the super class as well as sub class is same? will the variables be hidden than how?or the variables will be overridden? i am bit confused on this point please if you could ellaborate and explain it will be kinda of you. Thanks in advance.
To my way of thinking it is just a matter of terminology. If you "widen your view" a bit, hiding, in a WAY, IS overriding a variable....but our standard definitions/terminology don't call it that.
We override methods but we hide variables. It's just a matter of terminology.
I suppose it could have some difference down in the "guts" at runtime since the runtime might have some polymorphism related decisions to make on overridden methods and that MIGHT not be the same mechanism when a variable is hidden but I am only guessing because I am in WAY over my head at this point.
SCJP - 86% - June 11, 2009
well!! Mr Campbell i dont know if i am right or wrong please correct me if anything wrong. i tried the program it is giving the output x=99 the value of x is 99 in the class Bar which is a sub class ,,,,,whereas in the super class the value of x is 3 but it is initialised inside the default constructor and default constructor is called as class is initialised ............but here the value of x is not getting reflected in subclass although in the method print() the statement System.out.println consist of this.getClass().getname() but as per i know the "this" " keyword is used to refer to super class methods " is it so?
Frankly to say i am not at all sure with what is happening over here.......why this behaviour?
Please Mr Campbel could you explain the reason........
Try this change: becomesIn the subclass (Bar), x is 99, and that is what you print out. The x in the subclass hides the x in the superclass. The altered version I have just suggested will (I hope) make things clearer for you.