I have a problem with saving some variables from State abstract method into the File in Memento Pattern. The error is 'Non accessible in scope'.
Here are the pieces of code:
State class.
public abstract class State
{
protected int W;
public int getW()
{
return W;
}
public void setW(int w)
{
W = w;
}
}
Memento class.
public class Memento {
private int w, h;
private double health;
private FileWriterUtil fileWriter = new FileWriterUtil("data.txt");
private FileWriterCaretaker caretaker = new FileWriterCaretaker();
public void Save() {
//here is the error in two lines under.
w = state.State.this.getW();
h = state.State.this.getH();
String strI = Integer.toString(w);
String strII = Integer.toString(h);
String str = strI+strII;
fileWriter.write(str);
caretaker.save(fileWriter);
}
}
I know it shouldn't work, but how to solve it?
You have at least three problems.
First, you need to construct an instance of the State class someplace in your Momento class, maybe as a member in the constructor? I don't know what you are trying to accomplish.
Second, State is abstract so you are going to have to define a subclass that you can instantiate. something like this:
class MyState extends State...
And instantiate MyState.
Thirdly, State doesn't declare a getH() method. How do you expect to call that?
Oh, one more thing:
state.State.this
Your use of "this" doesn't seem right.