我不明白为什么当我尝试编译此代码时编译器显示错误:
class A
{
public static void f()
{
System.out.println("A.f()");
}
}
class B extends A
{
public static int f()
{
System.out.println("B.f()");
return 0;
}
}
A类和B类中的两个方法之间的区别是返回类型, 我读到 Java 阻止重写静态方法。 所以我期望编译器不应该显示任何错误,因为最初没有任何覆盖!!
最佳答案
Java Language Specification有以下规则:
8.4.8.3. Requirements in Overriding and Hiding
If a method declaration d1 with return type R1 overrides or hides the declaration of another method d2 with return type R2, then d1 must be return-type-substitutable (§8.4.5) for d2, or a compile-time error occurs.
This rule allows for covariant return types - refining the return type of a method when overriding it.
因此,即使该方法隐藏了父类(super class)并且不重写它,返回类型仍然必须兼容。
关于java - Java 是否会阻止重写静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21797404/