Method overloading with interface in Java

I have a behavior that I don't understand when overloaded 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 method called would be test(A) , but obviously it is test(I) .

I do not understand why. At runtime, my variable a is A even A inheriting I.

+4
source share
3 answers

Since the reference type has a value of I, although you have an object of type A.

A a = new A ();

the test (A a) {} method is called

According to JLS Chapter 15:

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

+6
source

The variable a is of type I - if you must use A a = new A(); , he will use the correct overloaded method.

+3
source

Consider the following scenario:

  interface Animal { } class Dog implements Animal{ public void dogMethod() {} } class Cat implements Animal{ public void catMethod() {} } public class Test { public static void test (Animal a) { System.out.println("Animal"); } public static void test (Dog d) { System.out.println("Dog"); } public static void test (Cat c) { System.out.println("Cat"); } public static void main(String[] args) { Animal a = new Cat(); Animal d = new Dog(); test(a); } } 

If test (a) printed β€œCat” and not (correctly) β€œAnimal” simply because it contains a reference to the Cat object, then you can call catMethod () on the Animal object, which makes no sense, Java selects the most applicable a method based on a type that is not related to a variable.

0
source

All Articles