简体   繁体   中英

Java Overload method with inherited interface

i'm trying to understand java behaviour. Using this interfaces :

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

I'm overloading a method like this :

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

When calling method with the following object :

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

Why does java use :

 public void method(IA a);

instead of

public void method(IB b);

?

Thanks

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

(Compare this with overriding, where the method implementation is chosen at execution time based on the actual type involved.)

The line

 IA a = new myClass();

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

 public class MyClass2 implements IA{}

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

in which case a is NOT an IB as in your example. So the compiler makes no assumptions about the type other than what you provide. So it has to call the method that accepts IA.

因为你传递“a”,这是一个IA论证。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM