java - 当我尝试重写父类的方法时出现错误。这是为什么?

标签 java oop

当我尝试编译 Child 类时,出现以下错误:

Child.java:2: method does not override or implement a method from a supertype
    @Override
    ^
1 error
<小时/>

这是为什么呢?我尝试在子类中重写父类的init

class Parent {
    public static void init() {
        System.out.println("From the parent class");
    }
}

class Child extends Parent{
    @Override
    public static void init() {
        System.out.println("From the child class");
    }
}

最佳答案

您无法重写静态方法 - you can only hide it 。因此,您只能将 @Override 注释应用于实例方法:

class Parent {
    public void init() {
        System.out.println("From the parent class");
    }
}

class Child extends Parent {
    @Override
    public void init() {
        System.out.println("From the child class");
    }
}

关于java - 当我尝试重写父类的方法时出现错误。这是为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15729342/

相关文章:

java - 使用 Java 8 和 lambda 转换为 Map

java - 四边形出现在其他人面前,而他们不在

python - 将类及其函数传递给另一个类

php - 您将如何前往 Zend Framework 项目中的购物车 "design"?

python - 随机列表中的对象属性在 Python 中不可访问

java - 在子类对象java上调用父类的方法

java - 选择“查询”,将出现在 Netbeans 和 mysql 中的组合框中

java.lang.ClassCastException - 访问对象数组的 Java 数组,如二维对象数组

java - 在哪里可以找到金属外观和感觉的图标和其他资源?

c# - 仅公开派生类中的一些继承方法