Is there a way to override class variables in Java?

后端 未结 17 1361
没有蜡笔的小新
没有蜡笔的小新 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:15

    only by overriding printMe():

    class Son extends Dad 
    {
        public void printMe() 
        {
            System.out.println("son");
        }
    }
    

    the reference to me in the Dad.printMe method implicitly points to the static field Dad.me, so one way or another you're changing what printMe does in Son...

提交回复
热议问题