[英]Java override abstract generic method
我有以下代碼
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
}
但是我不知道該怎么做,因為我不能用特定的東西覆蓋doEventStuff
。
有誰知道如何做到這一點?
目前還不清楚您要做什么,但也許您只需要使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)
{
...
}
}
您正在使用 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) {
}
}
或者更簡單,只有一個通用綁定......
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) {
}
}
這仍然不適合我。 我有以下代碼:
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) {
...
}
}
由於MyConcreteContainer
是通用Container
的實現,為什么我的編譯器沒有識別出我已經正確地覆蓋了doStuff
方法?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.