-1

Gym.java

public class Gym extends ActiveObject { 
    public void run() {
        ...
    }
}

GymController.java

public class GymController extends WindowController implements KeyListener{

    private Gym gym;

    public void begin() {
        Gym gym = new gym(canvas, new Location(dx, dy), delay, this);
    }

    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();

        if (key == KeyEvent.VK_SPACE) {
            gym.run();
        }
    }
}

There is an object and its moving code in Gym.java file... and I wanted to call that to GymController.java file's keyPressed method... so that the object moves when the user presses the space bar. How do I even link these two files in the first place...? But the compiler is giving me an error saying that it cannot find symbol. How can I call a method from another .java file into current file's keyPressed method properly, so that it compiles...?

progyammer
  • 1,498
  • 3
  • 17
  • 29
hihello
  • 1
  • 1
  • The instance variable `gym` is NOT initialized. You are creating a new `Gym` object in the begin method. Remove the class name before `gym` in the `begin()` method. It should be `gym = new Gym(...)` and not `Gym gym = new Gym(...)`. – progyammer Nov 16 '16 at 10:24
  • 1
    first of all: `new Gym` instead of `new gym` – Michal Korecki Nov 16 '16 at 10:27

1 Answers1

1

As pointed out by comments, your problem lies in:

public void begin() {
  Gym gym = new gym(canvas, new Location(dx, dy), delay, this);
}

And it should be:

public void begin() {
  gym = new Gym(canvas, new Location(dx, dy), delay, this);
}

First of all, new takes the class name, you are building an actual object from a "pattern". Then, doing Gym gym =... creates a local variable within the scope of your begin() method. It will be discarded on return from begin. If you just use gym or this.gym, it will assign the new instance to the member variable.

But be careful, your initial gym instance will create a new gymcontroller instance which will, in turn create a new gym instance. So the gym.run() will not use the same instance of gym than the one who created it. If that was your intention, you need to pass the this reference from gym to gymcontroller.

Eric Darchis
  • 24,537
  • 4
  • 28
  • 49