方法重载时的重复方法 [英] Duplicate Method while Method-Overloading

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

问题描述

以下代码给出编译错误,错误为Duplicate Method。

  static int test(int i){
返回1;
}

static String test(int i){
returnabc;
}

这是预期的,因为重载方法都具有相同的签名并且仅在返回类型。



但是下面的代码可以很好地编译,并带有警告:

  static int test1(List< Integer> l){
return 1;


static String test1(List< String> l){
returnabc;





$ b

因为我们知道Java泛型可以在Erasure上工作,代码,这两种方法具有完全相同的签名,并且与返回类型不同。



Furthur,令我惊讶的是下面的代码再次给出了编译错误:

  static int test1(List< Integer> l){
return 1;
}

static String test1(List l){
returnabc;

第二个代码是如何工作的,没有发生任何编译错误,尽管存在重复的方法?解决重载的方法是在编译时而不是运行时完成的,所以Java编译器会知道它们之间的差异在你的第二个例子中的两个之间。在第三个例子中,问题是 List< Integer> 也是 List ,所以它不会如果您传入 List< Integer> ,则知道使用哪一个。


Following code gives compilation error with error "Duplicate Method"

static int test(int i){
     return 1;
}

static String test(int i){
     return "abc";
}

This is expected as both the overloaded method have same signature and differ only in return type.

But the following code compiles fine with a warning:

static int test1(List<Integer> l){
    return 1;
}

static String test1(List<String> l){
    return "abc";
}

As, we know the Java Generics works on Erasure, which mean in byte-code, both these method have exactly the same signature and differs with return type.

Furthur, to my surprise the following code again gives compilation error:

static int test1(List<Integer> l){
    return 1;
}

static String test1(List l){
    return "abc";
}

How is the second code working fine without giving any compilation error, though there is duplicate method?

解决方案

Resolving overloaded methods is done at compile-time, rather than runtime, so the Java compiler would know the difference between the two in your second example. In your third example, the problem is that a List<Integer> is also a List, so it wouldn't know which one to use if you passed in a List<Integer>.

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

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