在一种方法中返回基类的各种实现

时间:2019-09-26 17:56:57

标签: java inheritance return-type

所以我有几种不同的State实现(StateImplementation和OtherStateImplementation)

如果发生某个事件,我需要返回一个新的实现。 该方法可以返回N个不同的实现。

public class State() {
    // Contains various methods
}

public class StateImplementation extends State {
    public State onEvent(String event){
        if(event.equals("foo")){
            return new OtherStateImplementation();
        } else {
            return this;
        }
    }
}

public class OtherStateImplementation extends State {
    // Second implementation
}

我该怎么做,因为如果这样做,类型将与返回类型不匹配。

0 个答案:

没有答案
相关问题