java - 降低静态方法的可见性

标签 java inheritance information-hiding

我知道 child 不能降低非静态方法的可见性,我理解为什么会这样。

不过我读过“静态方法可以通过其重新声明来隐藏”。然而,我不明白如何在 Java 中实现这一点。

这真的可能吗?如果是,怎么做到的(代码示例),为什么引入(这似乎与不降低界面可见性的原则相矛盾)?

最佳答案

简短的回答是:不,这是不可能的。你混淆了一些术语。 隐藏可访问性无关(这是您真正要问的,而不是可见性,它与范围阴影 并在 Chapter 6 of the Java Language Specification (JLS) 中讨论)。

现在是更长的答案。术语覆盖 适用于实例方法,而术语隐藏 适用于类 (static) 方法。来自Java Tutorial topic Overriding and Hiding Methods :

The distinction between hiding a static method and overriding an instance method has important implications:

  • The version of the overridden instance method that gets invoked is the one in the subclass.
  • The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.

这里的一些其他答案提供了关于方法隐藏的不正确示例,所以让我们回到 JLS,这次是 §8.4.8 :

Methods are overridden or hidden on a signature-by-signature basis.

也就是说,要覆盖或隐藏父类中的方法,子类必须定义具有相同签名的方法——基本上,相同数量和类型的参数(尽管泛型和类型删除使规则比这复杂一点)。还有关于返回类型和 throws 子句的规则,但这些似乎与这个问题无关。

请注意,您可以在子类中定义一个方法,其名称 与父类(或已实现的接口(interface))中的方法相同,但参数的数量或类型不同。在那种情况下,您重载方法名称,既不覆盖也不隐藏任何东西;子类方法是一种新方法,几乎​​独立于继承的方法。 (当编译器必须将方法与方法调用相匹配时会发生交互,仅此而已。)

现在回答您的问题:术语可访问性隐藏(以及可见性)在Java 中是独立的概念。正如您所说,有一个“原则”,即子类根本无法减少继承方法的可访问性。无论您是覆盖实例方法还是隐藏类方法,这都适用。来自 the JLS §8.4.8.3 :

The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows:

  • If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.

  • If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.

  • If the overridden or hidden method has default (package) access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.

总而言之,static 方法可以隐藏与改变方法的可访问性无关。

关于java - 降低静态方法的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26963828/

相关文章:

c - 信息隐藏如何阻止函数访问单个数组元素?

java - 网站上的小程序似乎讨厌包

java - 对动态代理的调用应该转到动态类型的方法还是静态类型的方法?

java - 有没有办法在过滤器内创建 Cookie 并将其添加到响应中?

php - 从子方法访问时,父方法设置的父类属性为空

python - 在实例化父类(super class)的python中进行子类化

c++ - 为类/信息隐藏创建内部和外部接口(interface)

oop - 信息隐藏 "Swifter"方式?

java - 无法使用 JBOSS EAP 7 将 EAR 文件部署到 Azure 应用服务

java - 单个模型元素在 UI 中多次表示...如何在 GEF 中实现?