java package private,我什么时候在Java中使用package-private?

I love access control in any language, but I find that in Java I almost never (if ever) use the package-private access modifier (or lack thereof).

I realize that inner classes can be private, protected, or package-private, but outer classes can only be package-private or public. Why can an outer class be package-private but not protected? What is the benefit of restricting classes/methods/fields to be seen by the entire package, but not subclasses?

解决方案

I use package-private classes and methods when I want to hide implementation details from users (and other classes) outside the package.

For example if I have an interface and a factory class that creates instances of that interface, I may have the implementation class as a separate file but mark it package-private so others can not use it, nor will it clutter the JavaDoc (if javadoc set to only show public).

If you seal your jar file, package-private methods can also help restrict who can access these methods. If a method is public or protected, subclasses can still see and call that method even if it's in a different package. (Unsealed jars allow anyone to make classes in your packages so they will get access to package-private or protected methods)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值