为什么下面的代码有错误?为什么重载不成功?
// signatures of the reset method at //1 and //2 after erasure will be different
// then why don't they overload?
public class Test<T>{
public static void main(String[] args) {
WordBox<String> city = new WordBox<String>("Skogland");
city.reset("waiting"); // error: ambiguous
}
}
class Box <T> {
private T theThing;
public Box( T t) { theThing = t; }
public void reset( T t) { theThing = t; } //1
}
class WordBox< S extends CharSequence > extends Box< String > {
public WordBox( S t) { super(t.toString().toLowerCase()); }
public void reset( S t) { super.reset(t.toString().toLowerCase()); } //2
}
// signatures of the reset method at //1 and //2 after erasure will be different
// then why don't they overload?
public class Test<T>{
public static void main(String[] args) {
WordBox<String> city = new WordBox<String>("Skogland");
city.reset("waiting"); // error: ambiguous
}
}
class Box <T> {
private T theThing;
public Box( T t) { theThing = t; }
public void reset( T t) { theThing = t; } //1
}
class WordBox< S extends CharSequence > extends Box< String > {
public WordBox( S t) { super(t.toString().toLowerCase()); }
public void reset( S t) { super.reset(t.toString().toLowerCase()); } //2
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
java.lang.String
扩展了CharSequence
,因此调用city.reset("waiting")
与WordBox.reset(S extends CharSequence)
和Box.reset(String)
。要解决此问题,您应该确保
WordBox.reset()
接受与Box.reset()
相同的类型,在这种情况下WordBox.reset()
覆盖Box.reset()
,或者相反,确保WordBox.reset()
接受与Word.reset 不重叠的类型()
,在这种情况下,WordBox.reset()
会重载Box.reset()
。在您给出的示例中,我感觉您可能希望WordBox.reset()
覆盖Box.reset()
。java.lang.String
extendsCharSequence
, so callingcity.reset("waiting")
matches bothWordBox.reset(S extends CharSequence)
andBox.reset(String)
.To fix the problem, you should either ensure
WordBox.reset()
accepts the same type asBox.reset()
, in which caseWordBox.reset()
overridesBox.reset()
, or, conversely, make sureWordBox.reset()
accepts a type that does not overlap withWord.reset()
, in which caseWordBox.reset()
overloadsBox.reset()
. In the example you give, I get the feeling you'd probably wantWordBox.reset()
to overrideBox.reset()
.