[英]Java override abstract generic method
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?有谁知道如何做到这一点?
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)
{
...
}
}
You're using generics but you are not providing a binding.您正在使用 generics 但您没有提供绑定。
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) {
}
}
This is still not working for me.这仍然不适合我。 I have the following code:
我有以下代码:
public interface Container<T extends MyEntity> {
...
}
public class MyConcreteContainer implements Container<MyContreteEntity> {
...
}
public abstract class MyAbstractClass<T extends MyEntity> {
public abstract String doStuff(Container<T> container);
}
public class MyConcreteEntity implements MyEntity {
...
}
public class MyConcreteImplementedClass extends MyAbstractClass<MyContreteEntity> {
@Override
public String doStuff(MyConcreteContainer container) {
...
}
}
Since MyConcreteContainer
IS AN implementation of the generic Container
, why is my comppiler not recognising that I have Overridden the doStuff
method correctly?由于
MyConcreteContainer
是通用Container
的实现,为什么我的编译器没有识别出我已经正确地覆盖了doStuff
方法?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.