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

Leave a Comment