class Dad
{
protected static String me = "dad";
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
protected static String me = "son";
}
public void doIt()
{
new Son().printMe();
}
The function doIt will print "dad". Is there a way to make it print "son"?
Yes, just override the
printMe()
method:In short, no, there is no way to override a class variable.
You do not override class variables in Java you hide them. Overriding is for instance methods. Hiding is different from overriding.
In the example you've given, by declaring the class variable with the name 'me' in class Son you hide the class variable it would have inherited from its superclass Dad with the same name 'me'. Hiding a variable in this way does not affect the value of the class variable 'me' in the superclass Dad.
For the second part of your question, of how to make it print "son", I'd set the value via the constructor. Although the code below departs from your original question quite a lot, I would write it something like this;
The JLS gives a lot more detail on hiding in section 8.3 - Field Declarations
only by overriding
printMe()
:the reference to
me
in theDad.printMe
method implicitly points to the static fieldDad.me
, so one way or another you're changing whatprintMe
does inSon
...Though it is true that class variables may only be hidden in subclasses, and not overridden, it is still possible to do what you want without overriding
printMe ()
in subclasses, and reflection is your friend. In the code below I omit exception handling for clarity. Please note that declaringme
asprotected
does not seem to have much sense in this context, as it is going to be hidden in subclasses...Yes. But as the variable is concerned it is overwrite (Giving new value to variable. Giving new definition to the function is Override).
Just don't declare the variable but initialize (change) in the constructor or static block.
The value will get reflected when using in the blocks of parent class
if the variable is static then change the value during initialization itself with static block,
or else change in constructor.
You can also change the value later in any blocks. It will get reflected in super class
... will print "son".