Is there a way to override class variables in Java?

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

    Of course using private attributes, and getters and setters would be the recommended thing to do, but I tested the following, and it works... See the comment in the code

    class Dad
    {
        protected static String me = "dad";
    
        public void printMe()
        {
            System.out.println(me);
        }
    }
    
    class Son extends Dad
    {
        protected static String me = "son";
    
        /* 
        Adding Method printMe() to this class, outputs son 
        even though Attribute me from class Dad can apparently not be overridden
        */
    
        public void printMe()
        {
            System.out.println(me);
        }
    }
    
    class Tester
    {
        public static void main(String[] arg)
        {
            new Son().printMe();
        }
    }
    

    Sooo ... did I just redefine the rules of inheritance or did I put Oracle into a tricky situation ? To me, protected static String me is clearly overridden, as you can see when you execute this program. Also, it does not make any sense to me why attributes should not be overridable.

提交回复
热议问题