2012-02-15 61 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