0

So I have a few different implementations of State (StateImplementation and OtherStateImplementation)

And I need to return a new implementation if a certain event happens. The method can return N amount of different implementations.

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
}

How would I go about doing this, as the types don't match the return type if I do it like this.

IBronchart
  • 55
  • 6
  • 1
    Side-note: See [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Jacob G. Sep 26 '19 at 18:01
  • Thanks, edited the question – IBronchart Sep 26 '19 at 18:03
  • 1
    Maybe use an interface instead of inheritance and it looks a little strange with an instance method for this in one of the state classes. What about a static method or a separate class – Joakim Danielson Sep 26 '19 at 18:04
  • 2
    Either I missed something, or ... the types *do* match: They both extend `State`, so from a method that is supposed to return a `State`, you can return a `StateImplementation` as well as an `OtherStateImplementation`. Maybe extending the question to an [MCVE] will help (although my gut feeling is that it will then become a duplicate...) – Marco13 Sep 26 '19 at 18:09
  • 2
    You could use generics like here: [How do I make the method return type generic?](//stackoverflow.com/q/450807) – Tom Sep 26 '19 at 18:14
  • 2
    You seem to be right, it does work when I try to make a minimal reproducible example Edit: I had a switch statement for event, but returning in default doesn't count. – IBronchart Sep 26 '19 at 18:14

0 Answers0