Overriding a super class's instance variables

后端 未结 9 1928
暗喜
暗喜 2020-11-30 07:47

Why are we not able to override an instance variable of a super class in a subclass?

9条回答
  •  心在旅途
    2020-11-30 08:01

    class Dad{
        public String name = "Dad";
    }
    class Son extends Dad{
        public String name = "Son";
        public String getName(){
            return this.name;
        }
    }
    

    From main() method if you call

    new Son().getName();
    

    will return "Son" This is how you can override the variable of super class.

提交回复
热议问题