1

I'm using Greenfoot at the moment, learning Java. I'm very noobish when it comes to static/non-static, and I'm iffy on instances also.

In Greenfoot, I have a world class, let's call it World. Now I have another class, named Car and one subclass, Redcar. Lastly, I have a Button class.

If you are familiar with Greenfoot, I've created an instance of Redcar, named redcar (just lowercase) and added it to World via addObject();

public World() { 

    super(1000, 200, 1); 

    Redcar redcar = new Redcar();
    Button button = new Button();

    addObject(redcar, 45, 45);
    addObject(button, 960, 175);
}

Within the Car class, which contains the following

public class Car extends Actor {

    int carSpeed = 0;

    public void drive() {
        carSpeed++;
        move(carSpeed);
    }
}

If called from Redcar, it will move the Redcar further each time drive is called. I want this to happen when Button is clicked on however. Within my World class, I want to set up something to the effect of this:

if (Greenfoot.mouseClicked(button)) {
    redcar.drive();
}

However, if that is put within the World constructor, it doesn't run when the Greenfoot project is run. I've tried putting it within a while loop, so that it continuously looks for the mouse click, but that doesn't work, in fact it actually crashes Greenfoot.

Sorry if this question is confusingly worded, I will touch it up if need be. Basically, my question is this. How can I call a class's method to work on an instance, FROM a different class? For instance, the drive() method working on redcar (instance) from the button class

Zbrezi
  • 23
  • 5

1 Answers1

0

Well, if I understand your question you need to give visibility to the instances; something like this,

private Redcar redcar;                   // <-- if you want to access redcar in World.
public World() { 
  super(1000, 200, 1); 
  redcar = new Redcar();                    // <-- Use the redcar field
  Button button = new Button(this, redcar); // <-- if you want to access this World  
                                            // instance and redcar in Button.
  addObject(redcar, 45, 45);
  addObject(button, 960, 175);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249