سؤال

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