子类中的 getter 和 setter

Joe*_*ler 5 java inheritance getter-setter

我只是在学习编程中的继承,我想知道您是否应该为每个子类中的实例变量编写覆盖的 getter 和 setter,或者您是否只使用从抽象父类继承的继承。

为每个子类中的继承变量编写 getter 和 setter 是不是很糟糕的代码?

Luc*_*tti 4

是的,如果您不需要在儿童班级中采取特殊行为,那就可以了。

认为:

class A {
   private String val;
   public String getVal() { return this.val }
   public void setVal(String newValue) { this.val = newValue }
}
class B extends A {
   // you already have access to getVal & setVal here, so it's useless to override them here
}
class C extends A {
   private String valCopy;

   @Override
   public void setVal(String newValue) {
      super(newValue);
      this.valCopy = newValue
      // new behavior so here it's ok to override
   }
}
Run Code Online (Sandbox Code Playgroud)