Question

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?

Était-ce utile?

La solution 2

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.

Autres conseils

If your class isn't mean to be extended, you can also try the default modifier. Protected allows access from all classes in the same package and from all classes that subclass your class. Default allows access only from inside the package. Check this for more information on access modifiers.

You should also consider using getters and setters.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top