Java少用静态_java-减少静态方法的可见性

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

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子句的规则,但这些规则似乎与该问题无关.

请注意,您可以在子类中定义与父类(或已实现的接口)中的方法同名的方法,但参数数量或类型不同.在这种情况下,您将重载方法名称,而不会覆盖或隐藏任何内容.子类方法是一种新方法,几乎??与继承的方法无关. (当编译器必须将方法与方法调用匹配时会发生交互,仅此而已.)

现在您的问题是:术语可访问性和隐藏(以及可见性)是Java中的独立概念.就像您所说的,“原则”是子类根本无法减少继承方法的可访问性.无论您是重写实例方法还是隐藏类方法,这都适用.从the JLS §8.4.8.3开始:

The access modifier (07004) 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.

总而言之,可以隐藏静态方法的事实与更改方法的可访问性无关.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值