Is there a way to override class variables in Java? Ask Question

Is there a way to override class variables in Java? Ask Question
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"?

ベストアンサー1

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.

質問の 2 番目の部分、つまり「son」を印刷する方法については、コンストラクターを介して値を設定します。以下のコードは元の質問からかなり離れていますが、次のように記述します。

public class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public void printName() {
        System.out.println(name);
    }
}

JLSでは、隠れるセクションについてさらに詳しく説明しています。8.3 - フィールド宣言

おすすめ記事