它写在任何地方都不能覆盖静态方法,但是当我尝试减少访问说明符时,从public到protected,它会产生错误.例如
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类中被覆盖?为什么我们说它隐藏/阴影而不是覆盖?
解决方法:
它遵循一些与覆盖相同的规则,但这并不意味着它是压倒一切的.在这种情况下,它是section 8.4.8.3 of the JLS中的规则,“覆盖和隐藏的要求”:
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;目标完全在编译时确定.
值得回顾8.4.8节的其余部分,它将覆盖定义为实例方法中出现的内容.
标签:java,override
来源: https://codeday.me/bug/20190729/1573497.html