为什么一类有效而另一类无效?
正如您所看到的,具有非 void 返回类型很重要。
class TestValid {
public String f(List<String> list) {
return null;
}
public Integer f(List<Integer> list) {
return null;
}
public void test() {
f(Arrays.asList("asdf"));
f(Arrays.asList(123));
}
}
class TestInvalid {
public void f(List<String> list) {
System.out.println("strings");
}
public void f(List<Integer> list) {
System.out.println("numbers");
}
}
As you can see, having a non void return type is important.
class TestValid {
public String f(List<String> list) {
return null;
}
public Integer f(List<Integer> list) {
return null;
}
public void test() {
f(Arrays.asList("asdf"));
f(Arrays.asList(123));
}
}
class TestInvalid {
public void f(List<String> list) {
System.out.println("strings");
}
public void f(List<Integer> list) {
System.out.println("numbers");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
TestValid
开头无效:所以返回类型是转移注意力的。如果在确定重载签名时考虑返回类型,那么它将有效,但目前它与以下内容一样无效:
如果您确实设法让
TestValid
进行编译,我很想知道您正在使用哪种编译器。TestValid
isn't valid to start with:So the return type is a red herring. If return types were taken into account in determining signatures for overloading, then it would be valid, but currently it's as invalid as this:
If you genuinely managed to get
TestValid
to compile, I'd be interested to know which compiler you're using.在第二种情况下,由于类型擦除,方法
f
在运行时无法区分。http://java.sun.com/docs/books/ tutorial/java/generics/erasure.html
因此它们都具有完全相同的签名。
In the second case, the methods
f
cannot be distinguished at runtime due to type-erasure.http://java.sun.com/docs/books/tutorial/java/generics/erasure.html
Thus they both have precisely the same signature.
在编译的类型擦除部分之后,
List
和List
都是真正的 List 类型;在 TestInvalid 中,您正在使用相同的运行时签名创建两个方法。After the type erasure part of compilation,
List<String>
andList<Integer>
are both really type List; in TestInvalid you are making two methods with the same runtime signature.JDK1.5之前不支持协变返回类型;想想 Object.clone() 方法。以下内容可能会引起您的兴趣:
Covariant return type prior to JDK1.5 was not supported; think of Object.clone() method. The following might be of interest:
对于 TestValid 类:() 或 new ArrayList() 。
这些功能似乎超载。如果调用者传递类型已定义的参数 List 对象,则不会出现编译时错误。例如:new ArrayList
因为类型擦除后的签名(返回类型和输入参数)不一样。
但是,如果您传入 new ArrayList(),您将收到编译时错误。
第二个定义违反了重载函数的基本原则,其中两个函数在类型擦除后具有相同的签名(返回类型和输入参数)。
For TestValid class:
the functions appear to be overloaded. You wont get a compile time error if the caller passes a parameter List object which is type defined.eg: new ArrayList<Integer>() or new ArrayList<String>().
as the signature (return type and input parameters) after type erasure is not same.
However you will get compile time error if the you pass in new ArrayList().
The second definition violates the basic principle of overloading a function where two functions with same signature (return type and input parameters) after type erasure.