Consider a certain class hierarchy consisting of a root class and some subclasses
R
|
.--+--+------.
| | ... |
S1 S2 ... Sn
Class R has a field x of a certain type, say X, which is not a simple type, that every subclass should inherit. Subclasses can do sorts of internal processing on field x as well as expose it as a property.
Sort of a discussion arose about which of these two coding style was preferrable:
1st solution
Have class R declare x as a private field and provide public getter and setter
class R {
....
private X x;
....
public X getX() { ... }
public void setX(X ax) { ... }
}
2nd solution
Have class R declare x as a protected field
Which one, in your opinion, could be the preferrable solution?
It depends what you want to allow to be done to the inner X. If you want it to be accessible/modifiable from outside make public get/set. But if you want them to be only modifiable by its subclasses then use protected and that is all. IMHO