0

Suppose I have a class A which defines a method bar(). The method bar() calls another method foo(). I then extend A in B and override foo() and do not override bar() (so it gets inherited). Which foo() is being called in these two cases?

A a = new B();
a.bar(); // A or B's foo called?

B b = new B();
b.bar(); // A or B's foo called?

4 Answers 4

3

Both uses use B's foo(). A a is just accessing B's methods since B is the instance.

Think of A a as the interface for the instance, in this case: new B()

Here's an example (in groovy): http://groovyconsole.appspot.com/script/616002

Sign up to request clarification or add additional context in comments.

Comments

1

In A a = new B(); and B b = new B();

a and b are instance of B class so both time b's foo() method will be called.

Because if method is overridden in child class (in this case, B class) then instance of child object will call that method present in it's own class not in parent's class (in this case, A class).

Comments

0

It will call the foo method of B for both cases. In java all method calls are dispatched dynamically - doesn't matter on what reference or context you call it - the method invocation will be based on the type of the object.

2 Comments

What you're saying is true in this case, but I would be careful saying "all method calls are dispatched dynamically." Java doesn't have multiple dispatch. If you have an overloaded method for example, the one that is called is not dynamic based on the runtime type of the arguments you pass in.
I said based on the type of the object on which method is invoked - not the type of arguments.
0

Method call only depends on the type of the object of which the method is called and not on the reference type which is used to call.

Since in your case, in both cases, the method of object of type B is to be called, both will call B's foo().

class C {
    public void foo() {
        System.out.println("foo in C");
    }

    public void bar() {
        System.out.println("calling foo");
        foo();
    }
}


class B extends C {
    public void foo() {
        System.out.println("foo in B");
    }
}


public class A {


    public static void main(final String[] args) {
        C c = new B();
        c.bar(); // C or B's foo called?

        B b = new B();
        b.bar(); // C or B's foo called?

    }

And the output is:

calling foo
foo in B
calling foo
foo in B

Comments

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.