Dikla Dikla - 5 months ago 10
Java Question

Is there a way to override class variables in Java?

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"?

Answer

You can overwrite the variable. 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,

class Son extends Dad {
    static { 
       me = 'son'; 
    }
}

or else change in constructor.

You can also change the value later in any blocks. It will get reflected in super class