关于方法调用的 Java 多态性的困惑

Confusion on Java Polymorphism regarding method calling

我遇到了这个Java问题

Consider the following classes:

​
public class Computer extends Mineral {
    public void b() {
        System.out.println("Computer b");
        super.b();
    }

    public void c() {
        System.out.println("Computer c");
    }
}
​
public class Mineral extends Vegetable {
    public void b() {
        System.out.println("Mineral b");
        a();
    }
}
​
public class Animal extends Mineral {
    public void a() {
        System.out.println("Animal a");
    }

    public void c() {
        b();
        System.out.println("Animal c");
    }
}
​
public class Vegetable {
    public void a() {
        System.out.println("Vegetable a");
    }
​
    public void b() {
        System.out.println("Vegetable b");
    }
}

Suppose the following variables are defined:

Vegetable var1 = new Computer();
Mineral   var2 = new Animal();
Vegetable var3 = new Mineral();
Object    var4 = new Mineral();

Indicate on each line below the output produced by each statement shown. If the statement produces more than one line of output indicate the line breaks with slashes as in a/b/c to indicate three lines of output with a followed by b followed by c. If the statement causes an error, write the word error to indicate this.

执行

var1.b()

我对输出感到困惑

仔细分析,我们一定注意到,在调用mineral的b()方法时:

public void b() {
        System.out.println("Mineral b");
        a();
    }

我们也在调用一个方法

a()

因此,使用class层次结构图,可以调用方法

Vegetable.a()

source

Vegetable var1 = new Computer(); 中,您有一个 Vegetable 类型的引用变量,指向一个 Computer 类型的对象。如果 Vegetable 是 Computer 的超类型,则赋值有效。

表达式var1.b()将是合法的(编译通过),如果引用变量(Vegetable)的类型有一个方法b()。如果 Vegetable 类型没有方法 b(),那么表达式将给出编译错误。

如果编译通过:在运行时,调用var1.b()将在变量var1指向的对象上调用b()方法(即 Computer 类型的实例)。 Computer.b() 覆盖 Mineral.b(),因此将调用该方法。