当我尝试编译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");
}
}
答案 0 :(得分:2)
您无法覆盖静态方法 - 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");
}
}
答案 1 :(得分:0)
您无法覆盖java中的静态方法。有关详细信息,请查看:Why doesn't Java allow overriding of static methods?