java - Java 是否会阻止重写静态方法?

标签 java static-methods overriding

我不明白为什么当我尝试编译此代码时编译器显示错误:

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/

相关文章:

c++ - 静态方法类实例化

javascript - 在 JavaScript 类中声明一个公共(public) "static"函数

java - 在不覆盖方法时使用 super.method() ?

java - Selenium 问题 - 弹出窗口

java - 将 RSA 公钥(1024 位)格式转换为 Java 的 DER ASN.1 公钥

java - 重构java中常见的静态方法

Django 管理保存覆盖

java - IntelliJ在运行项目时使用maven

java - 无法使用 JDK11 javac 为仅变量类文件创建 JNI 头文件