Вопрос

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?
Это было полезно?

Решение

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

Другие советы

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).

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.

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top