You can access A's version of x
like this:
((A)this).x
as long as x
wasn't declared private
in class A
. I've just tested it.
Note that for fields, there is no overriding (as there is for methods). Thus, for an object of class C, there will be three x
fields, but two of them can't be accessed normally because they are hidden by the other field named x
. But casting the object as above will allow you to get at it, if it would have been visible if not hidden.
I think it is very poor practice to declare fields of the same name in a class and its subclasses. It's confusing. It can happen legitimately if, say, you have a class A
and you later change the implementation of A
and add a new private field z
; in that case, it may not be possible to make sure no subclasses of A
already have a field z
, since you don't even always know what all the subclasses are (if A
is a class you've distributed publicly, for instance). I think it's for that reason that Java allows you to have fields of the same name, and why the hiding rules are the way they are, because it allows things like this to work without breaking all the other subclasses. Other than that, though, I recommend not having fields of the same name in superclasses and subclasses. Perhaps if they're all private
it might be OK, though.