Search code examples
javaabstract

Java abstract class - Should the instance variables be private or protected?


Should the instance variables be private or protected in java abstract class?

Simple question. I am trying to get more insight into the concept of abstraction in java. Thanks!


Solution

  • As a rule of thumb, go for non-final private variables. If your design calls for giving derived classes access to these variables, provide protected methods for accessing them.

    Using protected variables creates maintenance liability in all classes, abstract or not. As soon as someone inherits from your abstract class, your protected variables become exposed as if they were public. Here are some reasons why this variables should be avoided:

    • Inheriting classes can change your variables at will - this may go around variable validations set up by the abstract base class
    • Inheriting classes become dependent on variable names and types - this locks in the design choice that you made when defining protected variables.

    First rule does not apply to final variables because they cannot be changed, so the rule makes an exception for them. Second rule still applies, though, so you should be careful about defining protected variables, even in situations when they are final.