To put it simply as an example,
public abstract class AbstractFellow {
protected Thing buddy;
....
public class ConcreteFellow extends AbstractFellow {
public void someMethod() {
buddy.doSomething();
//OR
buddy = somethingElse;
//OR
somethingElse = buddy;
}
}
Is this bad practice?
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
buddyto 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
getBuddyand nosetBuddy), something that is not as easy to accomplish with a member (you can always set it to befinal, but then you prevent the super-class from changing it, too!)