What should the accessablity of Fields in a Abstract Class be?

后端 未结 2 1656
生来不讨喜
生来不讨喜 2021-01-23 16:08

To put it simply as an example,

public abstract class AbstractFellow {

    protected Thing buddy;
....

public class ConcreteFellow extends AbstractFellow {
            


        
相关标签:
2条回答
  • 2021-01-23 16:36

    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!)

    0 讨论(0)
  • 2021-01-23 16:43

    It depends on you domain model and why you creating and abstract class. If you are defining your interface with it and want abstract class to keep some functionality it`s ok.

    If you are just setting all the fields protected and then reusing them in your child classes. Well it depends, but I think a better way should be found. And it seems not very clear for your future reader to get data in the base class and all it's behavior in child classes. If you do not need base class ability to implement methods (and you do not need to store any functionality in your base class) maybe it`s a better choice to implement an interface with every of these child classes.

    If you use some of base class inner fields it seems natural to me and it's ok. Just if you are using some of them in your child classes for similar things you can implement a template method and enjoy with overriding only the parts you really need to override.

    0 讨论(0)
提交回复
热议问题