What is the use of package level protection in java?

前端 未结 15 1060
时光说笑
时光说笑 2020-12-05 14:28

I know how package level protection in java works. I read a lot of code (including lots of open source stuff) and no-one seem to be using it. The whole protection l

15条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 14:58

    It can be used for implementation classes, for one thing. For example, EnumSet is an abstract class, and no implementing classes are shown in the docs. Why? Because there are two implementing classes--one for enums with 64 or fewer elements, and one for 65 or more--and you don't really need to know which one you're using. In fact, you don't even need to know that there's more than one implementation. In fact, you don't even need to know that EnumSet is abstract--you just need to know that you can call one of the static methods and get a Set back.

    In this case, private internal classes might have sufficed (although unwieldy, especially for large classes). But sometimes other classes in a package would need access to such implementation details. protected could work, but then they would be open to subclasses also.

    In short, it covers an area of encapsulation that is not handled by the other three levels of protection.

提交回复
热议问题