Is there a way to override class variables in Java?

后端 未结 17 1311
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 09:49
class Dad
{
    protected static String me = \"dad\";

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

class Son extends Dad
{
    protected         


        
17条回答
  •  轮回少年
    2020-11-22 10:16

    https://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html

    It's called Hiding Fields

    From the link above

    Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different. Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through super, which is covered in the next section. Generally speaking, we don't recommend hiding fields as it makes code difficult to read.

提交回复
热议问题