java date the type is ambiguous_一个java ambiguous method 的问题

前段时间读一些代码,其中包含了若干复杂的implemens和extends关系,居然在调用时出现了the method *** is ambiguous for the type *** . 一直以为java中没有多继承,正常的多态怎么会造成这种问题。请看下面的场景:

public class AmbiguousExpector {

class A {

}

class B extends A implements IC{

}

interface IC {}

void test(A a){}

void test(IC b){}

void ambiguous(){

B b = new B();

test(b);

}

}

上述代码无法编译,

The method test(AmbiguousExpector.A) is ambiguous for the type AmbiguousExpector    AmbiguousExpector.java

line 20    Java Problem。

原因:

B extends A的同时implements IC,但是在Class AmbiguousExpector 中的test方法签名中,接受参数为A 或者 IC,不幸的是变量b此时既满足test(A a),又满足Test(IC b),所以产生了ambiguous的错误。

可以尝试注释掉任意一个test方法,编译都可以通过。或者增加test(B b).

上述错误当使用generic的时候可以扩展如下:

public class AmbiguousExpector {

class A {

}

class B extends A implements IC{

}

interface IC {}

void test(T a){}

void test(V b){}

//    void test(A a){}

//    void test(IC b){}

void ambiguous(){

B a = new B();

test(a);

}

}

结果一样。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值