Java为什么限制隐藏方法的访问修饰符 [英] Why does Java restrict the access modifier of a hiding method

查看:115
本文介绍了Java为什么限制隐藏方法的访问修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

隐藏静态字段时,对该字段在子类中的访问级别没有限制,甚至可以是非静态的,也可以是其他数据类型.

When hiding a static field, there's no restriction on what access level does the field have in subclass, it can be even non-static and of other data type.

另一方面,当隐藏静态方法时,子类中的静态方法(比父类中隐藏静态方法)可以比隐藏方法具有更多但并非更少的访问权限.

On the other side, when hiding a static method, the static method from subclass that hides the static method from superclass can allow more, but not less, access than the hidden method.

AFAIK,静态方法链接总是在编译时完成的,那么为什么会有这样的限制?

AFAIK, static method linking is anyway done at compile time, so why is there such a restriction ?

P.S.问题只是出于好奇.

P.S. The question is just out of curiosity.

推荐答案

因为在子类中,您覆盖了非私有超类方法,但覆盖了阴影字段.至于设置更广泛的访问级别,您总是可以这样写

Because in subclass you override non private superclass method but shadow fields. As for setting broader access level - you always could write something like

public void sublcassMethod() {
    supersecretSuperclassMethod();
}

因此,没有必要在语言级别使用更广泛的访问来限制覆盖-这种限制很容易实现

so there is no sense to restrict overriding with more broader access at language level - such restriction can be easy committed

这篇关于Java为什么限制隐藏方法的访问修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆