2012-08-14 42 views
2

我已閱讀約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) { 
      //... 
     }  
    } 

}

+0

'公共靜態CommandParser createParser(字符串命令)拋出異常{ 開關(命令){' 你怎麼能有一個'String'開關? – SiB 2012-08-14 16:44:37

+1

@BharatSinha:http://java.dzone.com/articles/new-java-7-feature-string - 請注意,Java 7已超過現在... – 2012-08-14 16:47:49

+0

謝謝。我不知道! – SiB 2012-08-14 16:49:04

回答

3

CommandParser內部類這意味着它需要創建一個外部類的實例(ProtocolUtility)。它的聲明更改爲:

public static abstract class CommandParser { 

在一個單獨的文件.java聲明或者CommandParser

如果createParser()不是static,您的代碼也可以工作,因爲在這種情況下,您當前所在的實例爲ProtocolUtility將用作外部實例。

1

createParser被稱爲靜態的方式(即ProtocolUtility.createParser(...)),你不能從被內部ProtocolUtility定義爲需要你有這個類的一個實例類實例化對象(你沒有)。這可以通過使內部類static來解決。

0

因爲CommandParser1()不是靜態的。您需要CommandParser1的一個實例來調用CommandParser1()或將其定義爲靜態。

0

Static method無法訪問一個Non-static method or variable.

您的代碼return new CommandParser1(command);靜態方法public staticCommandParser createParser(String command)裏面,所以這就是導致錯誤。

2.而當你試圖訪問CommandParser1(command)這是class ProtocolUtilityinner class這是它的outer class您可以直接訪問它,你在做什麼,現在 但是假設,當你試圖使ProtocolUtility class以外的地方訪問它,然後您需要創建一個外部類實例以訪問此內部類方法。

+0

-1,減少你對帽子的使用和大膽 – 2012-08-14 19:02:29

+0

請不要介意使用帽子和粗體的假臉。重要的是內容;評論者已根據我的估計正確解釋了此問題。 – mozillanerd 2012-08-14 19:21:53

+0

@ Mark Rotteveel如果外觀對你來說比技術上正確的答案更重要,那麼最好加入一些管理領域。 – 2012-08-15 13:58:33

相關問題