2012-02-15 62 views
2

我正在創建一個基本的併發服務器,允許用戶使用Java NIO下載文件。在下載之前,用戶必須接受條款和條件。使用Java在擴展類中不共享的變量

問題似乎是我的state變量沒有在我的ServerProtocol類中更新,儘管在我的Terms類中更新了它。擴展課程時是否不會共享這些變量?

public class ServerProtocol { 

    private static final int TERMS = 0; 
    public static final int ACCEPTTERMS = 1; 
    private static final int ANOTHER = 2; 
    private static final int OPTIONS = 3; 
    public int state = TERMS; 

    public String processInput(String theInput) throws FileNotFoundException, IOException { 
     String theOutput = null; 

     switch (state) { 
      case TERMS: 
       theOutput = terms(); 
       break; 
      case ACCEPTTERMS: 
       ........ 
} 

private String terms() { 
     String theOutput; 
     theOutput = "Terms of reference. Do you accept? Y or N "; 
     state = ACCEPTTERMS; 

     return theOutput; 
    } 

在上述情況下,用戶輸入Y或N對應於theOutput串和狀態被設置爲ACCEPTTERMS和執行中的代碼。這工作正常。

但是,我想分開疑慮並創建一個類來保存條款和條件以及其他相關方法。

我產生以下:

public class ServerProtocol { 

    public static final int TERMS = 0; 
    public static final int ACCEPTTERMS = 1; 
    public static final int ANOTHER = 2; 
    public static final int OPTIONS = 3; 
    public int state = TERMS; 

    public String processInput(String theInput) throws FileNotFoundException, IOException { 
     String theOutput = null; 
     Terms t = new Terms(); 

     switch (state) { 
      case TERMS: 
       theOutput = t.terms(); 
       state = ACCEPTTERMS; // I want to remove this line // 
       break; 
      case ACCEPTTERMS: 
       ....... 
}  

public class Terms extends ServerProtocol { 

    private String theOutput; 
    private static final String TERMS_OF_REFERENCE = "Terms of reference. Do you accept? Y on N "; 

    public String terms() { 
     theOutput = termsOfReference(); 
     // state = ACCEPTTERMS; // and add it here // 
     return theOutput; 
    } 

    public String termsOfReference() { 
     return TERMS_OF_REFERENCE; 
    } 

其結果是:

terms()方法,而不是被設置到ACCEPTTERMSServerProtocol類的狀態的連續循環。我推測儘管延長了ServerProtocol班,ACCEPTTERMS變量不共享。任何想法爲什麼?

+1

我不確定你說的問題是什麼;如果ACCEPTTERMS不是「共享」的,你將無法編譯。你是說'國家'沒有更新? – 2012-02-15 18:52:06

+0

@DaveNewton是的。 '國家'沒有被更新。感謝您的更正 – keenProgrammer 2012-02-15 19:01:10

+0

此外,我不清楚爲什麼'Terms'是一個子類;看起來有點奇怪,你正在實例化當前類的子類才能工作。我可能會考慮別的。 – 2012-02-15 19:04:42

回答

0

要在兩個實例之間共享狀態成員,它必須是靜態的...

+0

(我最初誤讀了,儘管我會將語句改爲「兩個實例」 - 這不是說'Terms'類不能訪問'state'(因爲它),而是它是一個不同的實例。 ) – 2012-02-15 19:02:12

+0

「public static int state = TERMS'會使它工作是正確的。但是我認爲在整個JVM中只有一個狀態並不是解決問題的最好方法。 – extraneon 2012-02-15 19:04:01

+0

同意這兩個意見... – assylias 2012-02-15 19:26:13