Java overload method with legacy interface

I am trying to understand the behavior of Java. Using these interfaces:

public interface IA {} public interface IB extends IA {} public class myClass implements IB {} 

I overload this method:

 public void method(IA a); public void method(IB b); 

When calling a method with the following object:

 IA a = new myClass(); method(a); 

Why use java:

  public void method(IA a); 

instead

 public void method(IB b); 

?

thanks

+4
source share
3 answers

Because the compiler only knows that a is an instance of IA . Overloads are determined at compile time based on the compilation time types of the corresponding expressions, and the compilation time type a is equal to IA .

(Compare this with the redefinition where the method implementation is chosen at runtime based on the actual type involved.)

+14
source

Line

  IA a = new myClass(); 

defines object a as type IA and all that the compiler knows. He cannot assume that a is also IB, because it is entirely possible for this:

  public class MyClass2 implements IA{} IA a = new MyClass2(); method(a); 

in this case, a is not IB, as in your example. Therefore, the compiler makes no assumptions about the type other than what you provide. Therefore, it must call a method that accepts IA.

+4
source

Because you pass "a", which is an IA argument.

+3
source

All Articles