BrownBear2018
BrownBear2018

Reputation: 57

Java Inheritance, Dynamic Dispatch Exam Question

This is a question from UW CSE 143. I am just studying past exams to get better at Java.

    public class Box extends Pill {

        public void method2() {
            System.out.println("Box 2");
        }

        public void method3() {
            method2();
            System.out.println("Box 3");
        }

    }

    public class Cup extends Box {

        public void method1() {
            System.out.println("Cup 1");
        }

        public void method2() {
            System.out.println("Cup 2");
            super.method2();
        }

    }

    Box var3 = new Cup();

Question: What is the outprint if var3.method3() is called?

I have no idea why the answer is Cup 2/Box 2/Box 3

Where is cup 2 from? I get the dynamic type is Cup. But if Cup class does not have method3, so it goes to the parent class for method3.

Upvotes: 1

Views: 126

Answers (1)

Eran
Eran

Reputation: 394096

var3.method3()

executes the Box method (since Cup doesn't override that method):

public void method3() {
    method2();
    System.out.println("Box 3");
}

method2() executes Cup's method2(), since the dynamic type of var3 is Cup, and Cup overrides method2() of Box:

public void method2() {
    System.out.println("Cup 2");
    super.method2();
}

This prints "Cup 2" and then super.method2() executes the super class method:

public void method2() {
    System.out.println("Box 2");
}

This prints "Box 2".

Finally, when we return to method3(), "Box 3" is printed.

Hence the output is

Cup 2
Box 2
Box 3.

Upvotes: 1

Related Questions