Is there a way to override class variables in Java?

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

    Yes. But as the variable is concerned it is overwrite (Giving new value to variable. Giving new definition to the function is Override).Just don't declare the variable but initialize (change) in the constructor or static block.

    The value will get reflected when using in the blocks of parent class

    if the variable is static then change the value during initialization itself with static block,

    class Son extends Dad {
        static { 
           me = 'son'; 
        }
    }
    

    or else change in constructor.

    You can also change the value later in any blocks. It will get reflected in super class

提交回复
热议问题