Search code examples
javaprotected

Protected usage to share variable in package


Is protected attribute a valid method (best pratice) to use (read and modify) variables in various classes of the same package, or is there any motivation to don't do this?


Solution

  • This is one of the main intentions of protected. The other one is for usage in sub-classes. So yes, this is a good way of doing it. But ... I would use protected (getter/setter) methods instead, if possible. Don't have the variables themselves as protected, and don't modify them directly.