Pros and cons of package private classes in Java?

2019-01-05 02:48发布

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:

  1. I seldom see the use of package-private class. Is there a reason for this, e.g., it has serious drawbacks, it is redundant, or simply I am not reading enough? Are there strong arguments for/against its usage?

  2. If it is really not useful in most cases, why would it be the default?

  3. In what situation should we use package-private in the real world? I.e., when would it become irreplaceable?

In other words, what are the major pros and cons of the default package-private modifier?

8条回答
该账号已被封号
2楼-- · 2019-01-05 03:35

One nice thing about package-private is that you can use it to give access to methods you would otherwise consider private to unit test classes. The downside of course being that other classes in the package could call it when they really shouldn't.

查看更多
Viruses.
3楼-- · 2019-01-05 03:35

"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."

查看更多
登录 后发表回答