I’m creating a basic concurrent server allowing a user to download a file using Java NIO. Prior to downloading the user must accept the terms and conditions.
The problem appears to be that my state variable is not being updated in my ServerProtocol class despite updating it in my Terms class. Are these variables not shared when extending a class?
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;
}
In the above scenario, the user enters Y or N corresponding to theOutput string and the state is set to ACCEPTTERMS and executes the code within. That works fine.
However, I wanted to separate concerns and create a class to hold the terms and conditions and other related methods.
I produce the following:
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;
}
The result:
A continuous loop of the terms() method and the state not being set to ACCEPTTERMS in the ServerProtocol class. I presume that despite extended the ServerProtocol class, the ACCEPTTERMS variable is not shared. Any ideas why?
To share the state member between two instances it would have to be static…