考虑下面的java代码:
class Enclosing {
void method(){}
void method(String str){}
class Inner {
void method(){}
}
}
我正在读一本书,它告诉我 Inner.method()
将隐藏 Enclosing.method()
的两个版本,这意味着如果我在类 Inner
的某处调用 method(aString)
。
为什么语言要这样设计?
更新:
根据@Debosmit Ray 给出的答案,与shadowing有关。我已阅读文档并了解它是什么。
仍然让我困惑的是为什么方法隐藏是基于方法名而不是方法签名?
最佳答案
非静态嵌套类或内部类被用作对仅在一个地方使用的类进行逻辑分组的一种方式;它使代码更具可读性并促进封装。
来自 [ docs ],
If a declaration of a type (such as a member variable or a parameter name) in a particular scope (such as an inner class or a method definition) has the same name as another declaration in the enclosing scope, then the declaration shadows the declaration of the enclosing scope.
这里的阴影意味着如果你在外部类中有一个变量x
,而在内部类中有另一个变量x
,修改x
在内部类中不会影响外部类中的x
。
我很喜欢这个问题和你提出的观点。我的解释对你理解有帮助吗?
关于java - 为什么内部类方法隐藏所有同名的封闭类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36077686/