Would it be right to leave the attributes of the abstract class as private or protected?

Asked

Viewed 568 times

13

I don’t know how I should leave these attributes.

1 answer

12


It depends on what you want. If you leave the derived class private you will not be able to access them directly, this is usually what you want. If the derivative needs to access the field directly for something, leave it protected. Indirectly (through a protected or public method) it is clear that it can be accessed.

Some say that the protected nor should it exist in language. I think it is an exaggeration, but it gives an indication that it should be used sparingly. Many think that it is either public or private. I prefer to have more granularity. Only experience will indicate when something should really be protected without causing problems. So some prefer never to have protected attributes. Private field always gives more freedom to those who draw the abstract (or normal) class. Private is implementation detail. The protected already creates a coupling that may be unnecessary or even harmful in some cases.

I’m not a fan of the term attribute for this, I prefer field.

  • 1

    There is also the case where the attribute interests the subclass but you don’t want it to have the power to change the value of the attribute. Then you can declare the attribute as protected final. But sometimes it is not possible because who sets the initial value of the attribute is the superclass. There you can leave it private, but provide a method protected getAtributo() which gives read-only access to its value by subclasses.

  • Sometimes the attribute only matters, or rather is only used, by code within the abstract class. And there’s the situation that I’ve spoken about too.

  • 1

    And also to say that the abstract class only serves to make inheritance is not very accurate. It serves to provide a partial implementation that has use for subclasses, but even this partial implementation may have internal details that only interest the abstract class. (@bigown, sorry I crossed the answer and answered the comments, but the reasoning was in the career here :-)

  • But I liked your comments Piovezan : /

  • 1

    @Piovezan that’s it, just helped. Can answer too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.