Strange case of static method override in java

坚强是说给别人听的谎言 提交于 2019-11-28 08:49:18

问题


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();            
    }
}

It says

Cannot reduce the visibility of the inherited method

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?


回答1:


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":

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

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.

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




回答2:


You yourself posted answer in your question, overriding means having different code in child class for same method. As static methods cannot be overridden you cannot play with the visibility by modifying access specifiers.



来源:https://stackoverflow.com/questions/10297252/strange-case-of-static-method-override-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!