Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two methods which one will be chosen [duplicate]

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?

like image 667
Tschallacka Avatar asked Mar 24 '26 08:03

Tschallacka


1 Answers

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.

like image 163
Bohemian Avatar answered Mar 26 '26 22:03

Bohemian