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?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With