我正在创建一个基本的并发服务器,允许用户使用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()
方法,而不是被设置到ACCEPTTERMS
在ServerProtocol
类的状态的连续循环。我推测尽管延长了ServerProtocol
班,ACCEPTTERMS
变量不共享。任何想法为什么?
我不确定你说的问题是什么;如果ACCEPTTERMS不是“共享”的,你将无法编译。你是说'国家'没有更新? – 2012-02-15 18:52:06
@DaveNewton是的。 '国家'没有被更新。感谢您的更正 – keenProgrammer 2012-02-15 19:01:10
此外,我不清楚为什么'Terms'是一个子类;看起来有点奇怪,你正在实例化当前类的子类才能工作。我可能会考虑别的。 – 2012-02-15 19:04:42