为什么Java中没有子类可见性修饰符? [英] Why is there no sub-class visibility modifier in Java?

查看:427
本文介绍了为什么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

然而,Java的设计者只给了我 this

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.

为了完全清楚,我知道在Java中这样的修饰符不可能。我的问题是为什么这样的修饰符不包含在Java中? (对我来说)似乎是比 protected 或默认值更自然的可见性级别。原因是它的重要性不足以被包括在内,还是与我未考虑的可能副作用更相关?

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.

(顺便说一下, protected 子类和包,因为非静态保护方法(如果不在同一个包中)不能在声明类的任意对象上调用,而只能在对象上调用代码所在的子类。(你可以在 Object.clone()上看到这个,它只能被克隆对象的类调用。))

(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.))

这篇关于为什么Java中没有子类可见性修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆