问题描述
我正在阅读一些Java文本,文中说我们只能应用 public
或默认
访问修饰符类和接口。因此,如果我们声明它是一个编译错误:
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 {}
或
protected class A{}
我只是好奇为什么类或接口无法接收 private
或 protected
访问修饰符?
I am just curious why a class or an interface cannot receive private
or protected
access modifiers?
推荐答案
private
表示仅在封闭类中可见。
private
means "only visible within the enclosing class".
protected
表示仅在封闭类和任何子类中可见,并且也在封闭类的包中的任何位置。
protected
means "only visible within the enclosing class and any subclasses, and also anywhere in the enclosing class's package".
private
protected 定义的第一部分。 protected
的第二部分可以应用,但它由默认(包受保护)修饰符覆盖,因此 protected
部分无意义且部分冗余。
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.
private
和 protected
可以(并经常)应用于嵌套类和接口,而不是顶级类和接口。
Both private
and protected
can be (and frequently are) applied to nested classes and interfaces, just never top-level classes and interfaces.
这篇关于为什么类或接口不能接收私有或受保护的访问修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!