Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getters and setters in child classes

I am just learning about inheritance in programming and i was wondering if you should write overridden getters and setters for instance variables in each child class, or if you just use the inherited one from the abstract parent class.

Would it be bad code to write getters and setters for inherited variables in each subclass?

like image 827
Joe Butler Avatar asked Oct 16 '22 12:10

Joe Butler


1 Answers

Yes, it would if you don't need special behavior in the child class.

Suppose:

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
   }
}
like image 162
Luca Nicoletti Avatar answered Nov 13 '22 21:11

Luca Nicoletti