Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

language design - Why is there no sub-class visibility modifier in 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...