Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overloading with interface in Java

I have a behaviour that I don't understand with overloading in Java.

Here is my code:

interface I {}

class A implements I {}

class B {
   public void test(I i) {}

   public void test (A a) {}
}

When I call the following line:

 I a = new A();
 b.test(a);

I thought the called method would be test(A) but visibly it's test(I).

I don't understand why. In runtime my variable a is a A even A inherits I.

like image 436
Kiva Avatar asked Jan 15 '23 18:01

Kiva


2 Answers

Because the reference type is of I eventhough you have object of type A.

A a = new A();

will invoke method test (A a) {}

As per JLS Chapter 15:

The most specific method is chosen at compile-time; its descriptor determines what method is actually executed at run-time.

like image 154
kosa Avatar answered Jan 31 '23 11:01

kosa


The variable a is of type I -- if you were to use A a = new A(); it would use the correct overloaded method.

like image 31
Kevin Mangold Avatar answered Jan 31 '23 12:01

Kevin Mangold