有人可以解释一下下面的代码为什么无效并给我错误的原因。
/* Java program to show that if static methods are redefined by
a derived class, then it is not overriding but hidding. */
// Superclass
class Base {
// Static method in base class which will be hidden in subclass
public static void display() {
System.out.println("Static or class method from Base");
}
// Non-static method which will be overridden in derived class
public void print() {
System.out.println("Non-static or Instance method from Base");
}
}
// Subclass
class Derived extends Base {
// Static is removed here (Causes Compiler Error)
public void display() {
System.out.println("Non-static method from Derived");
}
// Static is added here (Causes Compiler Error)
public static void print() {
System.out.println("Static method from Derived");
}
}
答案 0 :(得分:3)
这是一个错误,仅仅是因为它被定义为不允许。
您不能override a static method with an instance method:
(实例方法的:)如果重写的方法
mA
是静态方法,则是编译时错误。
或hide an instance method with a static method:
如果静态方法隐藏实例方法,则是编译时错误。