java Java覆盖抽象泛型方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6586046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java override abstract generic method
提问by iuiz
I have the following code
我有以下代码
public abstract class Event {
public void fire(Object... args) {
// tell the event handler that if there are free resources it should call
// doEventStuff(args)
}
// this is not correct, but I basically want to be able to define a generic
// return type and be able to pass generic arguments. (T... args) would also
// be ok
public abstract <T, V> V doEventStuff(T args);
}
public class A extends Event {
// This is what I want to do
@Overide
public String doEventStuff(String str) {
if(str == "foo") {
return "bar";
} else {
return "fail";
}
}
}
somewhere() {
EventHandler eh = new EventHandler();
Event a = new A();
eh.add(a);
System.out.println(a.fire("foo")); //output is bar
}
However I don't know how to do this, as I cannot override doEventStuff
with something specific.
但是我不知道该怎么做,因为我不能doEventStuff
用特定的东西覆盖。
Does anyone know how to do this?
有谁知道如何做到这一点?
回答by Jon Skeet
It's not really clear what you're trying to do, but perhaps you just need to make Event
itself generic:
不太清楚你想要做什么,但也许你只需要让Event
自己通用:
public abstract class Event<T, V>
{
public abstract V doEventStuff(T args);
}
public class A extends Event<String, String>
{
@Override public String doEventStuff(String str)
{
...
}
}
回答by Michael J. Lee
You're using generics but you are not providing a binding.
您正在使用泛型,但没有提供绑定。
public abstract class Event<I, O> { // <-- I is input O is Output
public abstract O doEventStuff(I args);
}
public class A extends Event<String, String> { // <-- binding in the impl.
@Override
public String doEventStuff(String str) {
}
}
Or simpler with only one generic binding...
或者更简单,只有一个通用绑定......
public abstract class Event<T> { // <-- only one provided
public abstract T doEventStuff(T args);
}
public class A extends Event<String> { // <-- binding the impl.
@Override
public String doEventStuff(String str) {
}
}