Java页面提示无访问权限,为什么Java缺少访问权限说明符?

Does anyone understand why Java is missing:

An access specifier which allows access by the class and all subclasses, but NOT by other classes in the same package? (Protected-minus)

An access specifier which allows access by the class, all classes in the same package, AND all classes in any sub-package? (Default-plus)

An access specifier which adds classes in sub-packages to the entities currently allowed access by protected? (Protected-plus)

I wish I had more choices than protected and default. In particular, I'm interested in the Protected-plus option.

Say I want to use a Builder/Factory patterned class to produce an object with many links to other objects. The constructors on the objects are all default, because I want to force you to use the factory class to produce instances, in order to make sure the linking is done correctly. I want to group the factories in a sub-package to keep them all together and distinct from the objects they are instantiating---this just seems like a cleaner package structure to me.

No can do, currently. I have to put the builders in the same package as the objects they are constructing, in order to gain the access to defaults. But separating project.area.objects from project.area.objects.builders would be so nice.

So why is Java lacking these options? And, is there anyway to fake it?

解决方案

To answer your questions one at a time:

* An access specifier which allows access by the class and all subclasses, but NOT by other classes in the same package? (Protected-minus)

This was in Java 1.0 (private protected was the modifier) and removed. I'm not entirely clear on why, but it was definitely viewed as something not worth the hassle. The current arrangement makes all modifiers go from less restricted to more restricted which is simpler (as in less potential variation) which is a Java design goal.

* An access specifier which allows access by the class, all classes in the same package, AND all classes in any sub-package? (Default-plus)

* An access specifier which adds classes in sub-packages to the entities currently allowed access by protected? (Protected-plus)

These two are not available for a related reason. Java currently doesn't have a notion of a sub-package, it just pretends to by the fact that the regular file and jar based classloaders (as well as the compiler) follow the directory structure of the underlying file system to find files. Java will be addressing this more extensively with JSR 294 (the "superpackage") (as others have pointed out) which will give you much more granular control of what is published outside of the package (and therefore you could make things public if you want to, and it still would not be visible).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值