How to define constants/final variables in abstract superclasses but assign them in the subclass?

前端 未结 1 1874
伪装坚强ぢ
伪装坚强ぢ 2021-01-11 12:12

I have a abstract class where I want to declare final variables.

However, I want to assign the values to these variables only in the constructors of my sub-classes.<

相关标签:
1条回答
  • 2021-01-11 13:09

    You should define a constructor in your abstract class that takes a value for a and call this constructor from your sub classes. This way, you would ensure that your final attribute is always initialized.

    abstract class BaseClass {
        protected final int a;
    
        protected BaseClass(int a)
        {
            this.a = a;
        }
    }
    
    class SubClass extends BaseClass {
        public SubClass() {
            super(6);
        }
    }
    
    0 讨论(0)
提交回复
热议问题