Question

I'm trying to convert some c# code to java and I'm having a little difficulty.

I have the following code and I want to know how to implement the CurrentState line in Java.

public class StateMachine
{
    **public static State CurrentState { get; set; }**
    public enum State
    {
        Init,
        Data,
        Text,
        Close,
        Invalid
    }
}

This is my meager attempt to resolve the issue, but it isn't quite right.

    static State currentState;

public static void setCurrentState(State currentState)
{
    this.currentState = currentState;
}

public static State getCurrentState()
{
    return currentState;
}

Question has now been answered and here is the correct working code in case anyone wants to see it.

public static State currentState;

public static State getCurrentState()
{
    return currentState;
}

public static void setCurrentState(State newState)
{
    currentState = newState;
}

Using these getCurrentState and setCurrentState methods I can now easily implement this in a case statement which was the original goal.

Was it helpful?

Solution

To answer the basic question, you need to declare a backing field called state for the get and set.

public class StateMachine {

    // This is the missing part
    private static State state;

    public static State getState() {
       return state;
    }

    public static void setState(State newState) {
        state = newState;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top