java - 为什么内部类方法隐藏所有同名的封闭类方法?

标签 java inner-classes shadowing

考虑下面的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/

相关文章:

java - 有没有办法让 Java 中的匿名内部类达到 "lose"它们的范围?

java - 为什么内部类被迫实现其接口(interface)方法,即使外部类有它?

haskell - 绑定(bind)怎么可能遮蔽 `case of` block 中的现有绑定(bind)?

java - 在Java中使用paintComponent()方法显示JPEG图像

java - 缺少方法体抽象类

java - 使用字符串递归

Java - 这些是哪些类型的类;哪个是匿名内部类?

java - java中如何实例化一个成员类的数组

python - 从(或附近)具有相同名称的脚本导入库会引发 "AttributeError: module has no attribute"或 ImportError 或 NameError

java - 当参数与方法类中的格式完全相同时,调用方法时参数不兼容