Access levels for java class members

I understand that this is a very simple question, but it always bothered me. Since I understand things, if you declare a private field in Java, then it is not visible outside of this class. If it is protected, it is available for inherited classes and in only one package (correct me if one of these definitions is incorrect).

Does this mean that it is impossible to declare a field that is accessible only to inherited classes, and not to other not inherited classes in one package?

I appreciate that there are ways around this, but are there any cases where you would like to have this behavior?

Obviously, the above question applies to both methods and fields.

Many thanks.

+6
java encapsulation
source share
3 answers

See: http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
Package> Subclasses, you can never have a field visible only by subclasses, but not classes from the same package.

+11
source share

Basically:

  • private: Only accessible to the class.
  • public: Accessible by any class.
  • protected: accessible to the class, all inherited classes and classes of the current package (edited).
  • no scope defined: Available by all classes in the current package.

More info here .

+3
source share

Yes, Java secure access is a little strange in this way. I cannot immediately understand why this is desirable at all. Personally, this does not bother me for fields, since I do not like non-private fields (except for constants), but the same is true for other participants.

.NET does not have the concept of visibility of access to a package / namespace, but it does have an alternative that is an assembly (I think the "jar file" is not quite the same, but close). Honestly, I would like to have namespace visibility and deployment options, but it seems like I'm doomed to disappointment ...

+2
source share

All Articles