문제

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?

도움이 되었습니까?

해결책 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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top