开发者

Which method gets called when multiple overloads are legal?

Say you have an Interface A, and an Interface B. Let's say the Sprite class implements both interfaces.

Say there's another class that has a method foo(A object), and also has a method foo(B object).

Do both get call开发者_高级运维ed when I pass an instance of Sprite to the method foo()? If not, which has precedence?


With method overloading (as is in use here), the method to call is resolved at compile time, based on the (declared) type of the variable holding the Sprite.

Since the method call is ambiguous, this will fail to compile until you manually downcast the reference to resolve the ambiguity.


It's ambiguous. You'll need to cast to one of the interfaces.


   interface A {}

   interface B {}

   class Sprite implements A,B {}

   class Test{
      void foo(A a){}
      void foo(B b){}

      void test(){
       Sprite s = new Sprite();
       foo(s); // <-- compile time error (The method foo(A) is ambiguous for the type Test)
      }
   }


The general answer requires several pages to explain; see the relevant section in the language specification.

In the specific case you present, it just won't compile. But in other cases there are rules by which the compiler may prefer one overload to another and resolve the conflict.

The most important rule is that, in general, if one method is more specific than the others, that method is picked. Method A is more specific than method B if all possible invocations of method A would also compile if calling method B. This usually means that some of the formal parameter(s) of method A are subclassed from the corresponding formal parameter(s) in method B. There are a few cases where this won't apply, such as when auto-boxing or other "method conversion" would be required to make an argument fit in the otherwise "more specific" case. For specifics, see the spec.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜