0

Due to Dynamic Method Dispatch, on creating an object using Superclass reference and calling a method through this object that has been overridden in the subclass, the overridden method in subclass will be called instead of the original method in the super class. What will be the case if the overridden method has been overridden again in a further subclass?

For example let's say A is the parent class, B extends A and C extends B. Let's say a method void m1() has been written in A and then it is overridden in B and then again overridden in C. Now if we create and an object as follows-

  A obj = new B();
  obj.m1();

which method will be called? The one in B or the one in C?

3
  • This example won't work. A is not an instance of type B, So you can't assign A() to a B(). If a method is overridden in C, Class B does not care about it. So if you would swap your example to A obj = new B(); this should call the method implemented in B. But why did you not just type this into code to see what it does? Commented Mar 2, 2019 at 10:55
  • Yes sorry I have corrected it now. I meant to say A obj = new B(); Commented Mar 2, 2019 at 11:03
  • I just assume obj can be assigned an object of type B(if that is not the case we have a different problem). That given: well obj is assigned an object of type B. So the methods from this type B are called. Type C doesn't matter as you don't use it at all. Commented Mar 2, 2019 at 12:46

1 Answer 1

0

You could always try it yourself, but the answer is really simple: B's method will be called.

class A {
    public static void main(String a[]) {
        A obj = new B();
        obj.m();
    }
    void m() {
        System.out.println("It's A");
    }
}
class B extends A {
    @Override
    void m() {
        System.out.println("It's B");
    }
}
class C extends B {
    @Override
    void m() {
        System.out.println("It's C");
    }
}

Executing this program will print It's B. Note that the location of main does not matter.

With some thinking it should be clear that »C's method will be called« cannot be the answer; if it was, which method would be called once you add another class C2 extends B overriding method void m()?

In general, if you have obj.m(arguments) and want to find out which m will be executed use the following steps:

  1. Determine the runtime type of obj (in this case B).
  2. Look inside the corresponding class for a method m(type of arguments).
  3. If there is no such method, go to the super class and repeat 2.
Sign up to request clarification or add additional context in comments.

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.