Domanda

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?

È stato utile?

Soluzione 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.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top