javaclassinheritancepolymorphismclass-hierarchy

Confusion on Java Polymorphism regarding method calling


I am having trouble with this Java Question:

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.

For the execution of

var1.b()

I was confused about the output

Through careful analysis, we must notice that when we call the method b() of mineral:

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

We are also calling a method

a()

And therefore, using a class hierarachy diagram, can call the method

Vegetable.a()

source


Solution

  • In Vegetable var1 = new Computer();, you have a reference variable of type Vegetable, pointing to an object of type Computer. The assignment is valid, if Vegetable is a super-type of Computer.

    The expression var1.b() will be legal (compilation pass), if the type of the reference variable (Vegetable) has a method b(). If the Vegetable type doesn't have a method b(), then the expression will give a compilation error.

    If the compilation passes: at runtime, calling var1.b() will invoke the b() method on the object the variable var1 points to (that is, an instance of type Computer). Computer.b() overrides Mineral.b(), so that method will be invoked.