Overriding a super class's instance variables

后端 未结 9 1924
暗喜
暗喜 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:07

    He perhaps meant to try and override the value used to initialize the variable. For example,

    Instead of this (which is illegal)

    public abstract class A {
        String help = "**no help defined -- somebody should change that***";
        // ...
    }
    // ...
    public class B extends A {
        // ILLEGAL
        @Override
        String help = "some fancy help message for B";
        // ...
    }
    

    One should do

    public abstract class A {
        public String getHelp() {
            return "**no help defined -- somebody should change that***";
        }
        // ...
    }
    // ...
    public class B extends A {
        @Override
        public String getHelp() {
            return "some fancy help message for B";
        // ...
    }
    

提交回复
热议问题