Java-Can不能重写该方法,即使引用对象指向子类对象



我有另一个示例程序,它可以覆盖,但所有方法都有相同数量的参数。

class A {
int a;
// function with dummy parameters
void printArray(int i) {
System.out.println("A");
}
}
class B extends A {
//function with dummy parameters
void printArray(int i, int s) {
System.out.println("B");
}
}
public class JavaApplication5 {
public static void main(String[] args) {
A ob = new A();
B o2 = new B();
A o3;
o3 = o2;
o3.printArray(3, 2); // It says that it can not be applied to given type :(
}
}

如果您不希望出现任何错误,您需要告诉Java解释器o3是否能够通过强制转换调用printArray(3,2(。主要通过做

((B)o3).printArray(3,2);

此外,你所做的并不是压倒一切。(请注意,类A和类B中的方法参数不同(重写如下:

class A {
int a;
// function with dummy parameters
void printArray(int i){
System.out.println("A");
}
}
class B extends A {
//function with dummy parameters
@Override
void printArray(int i) {
System.out.println("B");
}
}
public class Example {
public static void main(String[] args) {
A ob = new A();
B o2 = new B();
A o3;
o3 = o2;
o3.printArray(3);
}
}

在这里,您不需要强制转换任何内容,因为类B覆盖了类A中的方法。就Java解释器而言,类A和类B的任何实例都可以调用printArray,所以对象o3是类A还是类B的实例都无关紧要。

相关内容

最新更新