1

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.

1
  • Please format the source code. Commented Jun 4, 2020 at 6:29

1 Answer 1

1
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.
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I am just surprised that method2() executes Cup's method2() because it is inside the box class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.