0

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?

1 Answers1

0

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.

Robert Moskal
  • 21,737
  • 8
  • 62
  • 86
  • I want to save the state of coordinates of the character in game, to gain possibility to load thiese variables (w and h) and load the game. :) As getH(), I have acrossed the problem in geetingW so I just did not implement getH yet. As second problem, I have some classes which extend from the State class. But it is not Memento class. –  Jan 09 '16 at 16:01
  • How can I refer to exact that State, not using state.State.this? I have no idea. :( –  Jan 09 '16 at 16:12