Home >Java >javaTutorial >Can Class Variables Be Overridden in Java?

Can Class Variables Be Overridden in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-02 12:24:12787browse

Can Class Variables Be Overridden in Java?

Overriding Class Variables in Java: A Misnomer

In Java, class variables cannot be overridden. Instead, what appears to be an overridden variable is, in reality, a hidden variable. To clarify this concept, we examine an example:

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(); // Prints "dad"
}

Here, the function doIt prints "dad" because the class variable me in Son merely hides the inherited me from Dad.

The key difference between overriding and hiding is that overriding replaces the parent method implementation with the child method implementation, while hiding simply makes the parent member inaccessible from the child class.

Therefore, there is no proper way to override a class variable. Instead, to print "son" in the given example, it is necessary to modify the constructor or pass the name parameter to the method as in:

public class Son extends Dad {
    private String me;

    public Son(String me) {
        this.me = me;
    }

    @Override
    public void printMe() {
        System.out.println(me);
    }
}

The above is the detailed content of Can Class Variables Be Overridden in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn