Search code examples
javaoopenumsfsm

JAVA - Changing non static Class Field in Member Enum's Function


I am trying to implement an FSM in Java. I have an FSM Class, which has a String field message, and an ENUM to manage the bot states. Here's a sample code.

public class fsmBot
{
    public String message;

    public enum BotStates
    {
        greeting
        {
            @Override
            public void message()
            {
                message = "Hi";
            }

            @Override
            public String nextState()
            {
                String nxtState = BotStates.state1.name();
                return nxtState;
            }
        },
        state1
        {
            @Override
            public void message()
            {
                fsmApplyLeave.message = "How are you?";
            }

            @Override
            public String nextState()
            {
                String nxtState = BotStates.state1.name();
                return nxtState;
            }
        };
    }
}

But, here I am getting an error when I am accessing String message, a field of my class fsmBot, in functions greeting() of the enum BotStates. I could make it work by making message static, but I require multiple instances of this fsmBot class running. Is there any way to do this?

*Edit1- Eclipse gives the following error in the editor - Cannot make a static reference to the non-static field message


Solution

  • enums are static classes, so you could do something like this:

    public class fsmBot
    {
        public String message;
    
        public enum BotStates
        {
            greeting
            {
                @Override
                public void message(fsmBot bot)
                {
                    bot.message = "Hi";
                }
    
                @Override
                public String nextState()
                {
                    String nxtState = state1.name();
                    return nxtState;
                }
            },
            state1
            {
                @Override
                public void message(fsmBot bot)
                {
                    bot.message = "How are you?";
                }
    
                @Override
                public String nextState()
                {
                    String nxtState = state1.name();
                    return nxtState;
                }
            };
    
            public abstract void message(fsmBot bot);
            public abstract String nextState();
        }
    }