I have two java classes.
class A {}
class B extends A {}
I have class that accepts these classes, but requires different implementation methods.
class Holder {
public void accept(A a) {} // choice 1
public void accept(B b) {} //choice 2
}
If I supply a holder with a B object, which method will it choose?
Looking at the code I'd go with choice 2, but choice 1 can also accept due to the inheritance.
So who can tell me the runtime logic of this?
In all cases, the most specific method is invoked.
If the type of the object being passed is B, then the B method will be invoked, but if a B instance is assigned to a variable of type A, the A method will be invoked:
A obj = new B();
accept(obj); // will invoke the A method
The runtime type of the object is not used to bind to the method, because Java is a statically typed language, method binding is done a compile time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With