当我尝试编译 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/