Opinions vary. My opinion is that even in abstract classes, using private members and protected accessors (i.e. protected getBuddy()
) is a better practice.
It allows for the same things encapsulation always allowed: to contain the logic of obtaining the "buddy" object in the super-class, and allowing you to change that logic without breaking all inheriting classes.
The super-class might not expect buddy
to be changed, either. For example, you might want to unregister listeners or do some other cleanup when that happens - having a setter method helps achieve that.
In addition, it obviously allows you to have Buddy as a read-only member (since you can provide only a getBuddy
and no setBuddy
), something that is not as easy to accomplish with a member (you can always set it to be final
, but then you prevent the super-class from changing it, too!)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…