I’ve read about non-static variable this cannot be referenced from a static context error but I don’t understand why I get it in my case (line return new CommandParser1(command);)?. I just create instance of class. That’s all. What is the problem?
public class ProtocolUtility {
public static CommandParser createParser(String command) throws Exception {
switch (command) {
case COMMAND_1:
return new CommandParser1(command);
case COMMAND_2:
return new CommandParser2(command);
default:
return null;
}
}
public abstract class CommandParser {
protected String command;
public String getCommand() {
return command;
}
}
public class CommandParser1 extends CommandParser {
public CommandParser1 (String command){
//...
}
}
public class CommandParser2 extends CommandParser {
public CommandParser2 (String command) {
//...
}
}
}
CommandParseris an inner class which means it needs an instance of outer class (ProtocolUtility) to be created. Change its declaration to:Alternatively declare
CommandParserin a separate.javafile.Your code would also work if
createParser()wasn’tstaticas in this case an instance ofProtocolUtilityyou are currently in would be used as an outer instance.