方法不明确 [英] The method is ambiguous

查看:96
本文介绍了方法不明确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解方法重载,但在以下示例中我无法理解以下代码错误的原因

I am trying to understand method overloading and I'm not able to understand the reason for the following code error in the following example

public class OverLoading_OverRiding {
     public static void main(String[] args) {
        OverLoading_OverRiding o = new OverLoading_OverRiding();
        o.sum(5, 5);
    }

    void sum(int i, long j) {   }
    void sum(long i, int j) {   }
}

我遇到错误:


方法sum(int,long)对于
OverLoading_OverRiding类型是模棱两可的。

The method sum(int, long) is ambiguous for the type OverLoading_OverRiding.

当我执行显式强制转换时

When i am performing explicit casting on the same example then it works:

    o.sum(5, (long)5);


推荐答案

问题是您的编译器不知道该使用哪种方法如果调用 o.sum(5,5);

The problem is that your compiler dont know which method to use if you call o.sum(5, 5);


  1. 他可以使用 void sum(int i,long j){} 将前5个作为int,将后5个作为long

  1. he could use void sum(int i, long j) { } where he takes the first 5 as int and the second 5 as long

他可以使用 void sum(long i,int j){}
,其中前5个为第二个5为int

he could use void sum(long i, int j) { } where he takes the first 5 as long and the second 5 as int

因为这两种方法在此示例中均有效,并且编译器始终需要恰好是一个有效选项,则会收到错误消息,提示您的方法不明确。

since both methods would be valid to use in this example and your compiler always needs exactly one valid option, you get the error msg that your method is ambiguous.

如果调用 o.sum(5 ,(long)5); 仅匹配方法 void sum(int i,long j){}

问题是,为什么您会以这种方式重载方法?
大多数情况下,重载用于以下可选参数:

The Question is, why would you overload a method this way? Mostly overloading is used for optional parameters like this:

void myMethod(int i) {}
void myMethod(int i, bool b) {}
void myMethod(int i, string s) {}

,所以您可以这样调用该方法:

so you could call this method like:

myMethod(42);
myMethod(42, true);
myMethod(42, "myString");

也许这会让您对方法重载有所了解。

Maybe this gives you an idea of method overloading.

这篇关于方法不明确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆