CRT TV
CRT TV

Reputation: 195

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?

Upvotes: 7

Views: 8393

Answers (2)

Luca Nicoletti
Luca Nicoletti

Reputation: 2417

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
   }
}

Upvotes: 5

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

Suppose we have a generic class Number that accepts any numerical value but we want to implement two different classes, say, PositiveNumber and NegativeNumber using Number class, we can override setter method and enforce that the number set will always be either positive or negative depending upon overridden class.

public class Number {
    private int num;

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }
}

public class PositiveNumber extends Number {

    @Override
    public void setNum(int num) {
        super.setNum(num > 0 ? num : -num);
    }

}

public class NegativeNumber extends Number {

    @Override
    public void setNum(int num) {
        super.setNum(num > 0 ? -num : num);
    }

}

Upvotes: 0

Related Questions