java中无修饰子类可以,为什么Java中没有子类可见性修饰符?

On more than one occasion I have found myself desiring a variable visibility that is not possible in Java. I wanted certain members to be visible within their own class and within any sub-classes, but not to the rest of the package or to the rest of the world. In other words, I wanted this:

Modifier Class Package Subclass World

sub-class Y N Y N

However, the designers of Java only gave me this:

Modifier Class Package Subclass World

public Y Y Y Y

protected Y Y Y N

no modifier Y Y N N

private Y N N N

The typical case when I want something like this is when creating an abstract class. Sometimes I find the abstract parent needs access to certain members, but concrete children do as well. I can give them this access by making the members protected, but that opens up accessibility to the rest of the package when I don't really want to.

To be fully clear, I know such a modifier is not possible in Java. My question is why is such a modifier not included in Java? It seems (to me) to be a more natural visibility level than either protected or the default. Is the reason just along the lines of it not being sufficiently important to be included, or is it more related to possible side effects that I haven't considered?

解决方案

I suppose they want to avoid the added complexity by having a non-linear access hierarchy.

You should have control over your package, so simply don't call these protected methods there.

(By the way, protected is not quite the same as sub-class and package, as non-static protected methods (if not in the same package) can't be called on arbitrary objects of the declaring class, but only on objects of the subclass the code is in. (You can see this on Object.clone(), which can only be called by the class whose object is being cloned.))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值