Is there a way to override class variables in Java? Is there a way to override class variables in Java? java java

Is there a way to override class variables in Java?


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;

public class Person {    private String name;    public Person(String name) {        this.name = name;    }    public void printName() {        System.out.println(name);    }}

The JLS gives a lot more detail on hiding in section 8.3 - Field Declarations


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,

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


Yes, just override the printMe() method:

class Son extends Dad {        public static final String me = "son";        @Override        public void printMe() {                System.out.println(me);        }}