【问题标题】:Java-Can't override the method even though reference object is pointing to the subclass object [duplicate]Java-即使引用对象指向子类对象也无法覆盖该方法[重复]
【发布时间】:2018-11-28 17:24:17
【问题描述】:

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

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 类型系统是静态的。 o3A 类型,因此它无法访问两个参数的方法。
  • 您的代码中根本没有发生覆盖。您只是想在 A 类型的变量上调用仅在 B 类中定义的方法。

标签: java inheritance


【解决方案1】:

如果您不希望出现任何错误,您需要告诉 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 类的实例。

【讨论】:

    猜你喜欢
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 2016-12-28
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多