0

Question: When an overridden method is called using a base reference that refers to a derived object, which version of the method is invoked at run-time?

I think it would be the method that was overridden, since its called by just a reference to the derived object; correct?

userb
  • 173
  • 2
  • 15

2 Answers2

1

Yes, method of the derived object will be called.

tec
  • 41
  • 9
1

Yes, derived object method will be called. Use the following example to experience.

public class Main {
  public static void main(String[] args) {
        B b = new B();
        print(b);
    }

    public static void print(A a) {
        System.out.println(a.run());
    }
}

class A{
    public String run () {
       return "A";
    }
}

class B extends A{
    public String run () {
        return "B";
    }
}
Eranda
  • 1,439
  • 1
  • 17
  • 30