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!