Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - Why can't a class or an interface receive private or protected access modifiers?

I am reading some Java text and the text says that we can only apply public or default access modifier for class and interface. Therefore, it is a compiling error if we declare:

private class A {}

or

protected class A{}

I am just curious why a class or an interface cannot receive private or protected access modifiers?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

private means "only visible within the enclosing class".

protected means "only visible within the enclosing class and any subclasses, and also anywhere in the enclosing class's package".

private, therefore, has no meaning when applied to a top-level class; the same goes for the first part of the definition of protected. The second part of protected could apply, but it is covered by the default (package-protected) modifier, so protected is part meaningless and part redundant.

Both private and protected can be (and frequently are) applied to nested classes and interfaces, just never top-level classes and interfaces.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...