java中静态方法覆盖的奇怪情况 [英] Strange case of static method override in java

查看:108
本文介绍了java中静态方法覆盖的奇怪情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随处写的静态方法无法覆盖,但是当我尝试减少访问说明符时,从公共到保护它会导致错误。例如

It is written everywhere that static method cannot be overriden, but when I try to reduce the access specifier say from public to protected it gives an error. for example

public class StaticOverrideFunda {

    public static void foo(){
        System.out.println("Parent Foo");
    }
}

public class B extends StaticOverrideFunda{


    protected static void foo(){
        System.out.println("Child Foo");
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        B.foo();            
    }
}

它说


无法降低继承方法的可见性

Cannot reduce the visibility of the inherited method

因此,它是跟随压倒一切的规则,我们怎么说foo没有在B级被覆盖?为什么我们说它隐藏/阴影而不是覆盖?

So insense it is following the overriding rules, how come we are saying foo is not being overridden in B class? Why do we say it is hiding/shadowing and not overriding?

推荐答案

它遵循一些相同的规则 as overriding,但这并不意味着 覆盖。在这种情况下,它是第8.4.8.3节中的规则of JLS ,覆盖和隐藏的要求:

It's following some of the same rules as overriding, but that doesn't mean it is overriding. In this case, it's the rules in section 8.4.8.3 of the JLS, "Requirements in Overriding and Hiding":


覆盖或隐藏的访问修饰符(§6.6)方法必须至少提供与重写或隐藏方法一样多的访问权限,如下所示:[...]

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: [...]

它仍然没有覆盖,因为该方法不会以多态方式调用 - 您无法编写一个有时最终调用 StaticOverrideFunda.foo 有时最终调用 B.foo ;目标完全在编译时确定。

It's still not overriding, as the method wouldn't be invoked polymorphically - you can't write a call which will sometimes end up calling StaticOverrideFunda.foo and sometimes end up calling B.foo; the target is determined entirely at compile time.

值得回顾8.4.8节的其余部分,其中定义覆盖为某些内容在实例方法上发生。

It would be worth reviewing the rest of section 8.4.8, which defines overriding as being something which occurs on instance methods.

这篇关于java中静态方法覆盖的奇怪情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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