我已閱讀約non-static variable this cannot be referenced from a static context
錯誤,但我不明白爲什麼我得到它在我的情況(行return new CommandParser1(command);
)?我只是創建類的實例。就這樣。問題是什麼?爲什麼我會收到錯誤「無法從靜態上下文中引用非靜態變量」?
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) {
//...
}
}
}
'公共靜態CommandParser createParser(字符串命令)拋出異常{ 開關(命令){' 你怎麼能有一個'String'開關? – SiB 2012-08-14 16:44:37
@BharatSinha:http://java.dzone.com/articles/new-java-7-feature-string - 請注意,Java 7已超過現在... – 2012-08-14 16:47:49
謝謝。我不知道! – SiB 2012-08-14 16:49:04