Pros and cons of package private classes in Java?

前端 未结 8 1762
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 05:05

I am learning Java recently, and I came across the notion of package-private classes, which is the default if we don\'t specify anything. But then I realized:

相关标签:
8条回答
  • 2020-11-27 05:39

    "Package Private" its used when you have several packages, and it means, other classes in the same package can access that class or class member as "public", classes in other packages cannot access, its like "private like them."

    0 讨论(0)
  • 2020-11-27 05:40

    Regarding the question of "why would it be the default,", in this context, the term "default" just means the absence of another qualifier. I guess they could have invented another keyword ("package" was already taken), but they didn't.

    In the real world, I use default access for utility classes and abstract classes that I don't want people to call or otherwise use from other packages. Let's say you have an interface and two concrete implementations that extend from some abstract class. You declare your two concrete classes as final because you don't necessarily want people to subclass them (see Effective Java). You also don't want people to monkey around with your abstract class for the same reason. If you use default access for the abstract class, then people only see it if they put their class in your package. It's not bullet proof, but I think it's a reasonable use/illustration of default access. That said, the fact that it does not prevent the details from leaking as private would, i.e. doesn't guarantee anything, means that it's not a particularly useful convention.

    Another reason why you haven't see it used more often is that people tend to exclude classes with default access from their javadocs.

    0 讨论(0)
提交回复
热议问题