slickjer
slickjer

Reputation: 3

How do I access an object I've instantiated in my main method from another method?

I'm sure I'm missing something silly, here is my code:

public class clearBlankGrid {

    public static void main(String args[]) {

        Monster myMonster = new Monster(10,10,5,5,1);
        MonsterGUI myGUI = new MonsterGUI(myMonster);

        if (myMonster.getRows() > 0) {   
            // 0 = North, 1 = East, 2 = South, 3 = West
            myMonster.setFacing(3);
            myMonster.setIcon();
        }

    }

    public static void keepClearing() {

        myMonster.isGridCleared(); // Cannot find symbol 'myMonster'

    }

}

Upvotes: 0

Views: 107

Answers (4)

Martin
Martin

Reputation: 7139

myMonster needs to be a static member if you want to access it in the keepClearing method (which is static).

Note: For reference you could also avoid making the Monster member static by actually instantiating your clearBlankGrid class. Monster can then be an instance variable of clearBlankGrid which means the keepClearing method no longer has to be static.

public class clearBlankGrid {

   private Monster myMonster;
   private MonsterGUI myGUI;

   public void run() {
       myMonster = new Monster(10,10,5,5,1);
       myGUI = new MonsterGUI(myMonster);

       if (myMonster.getRows() > 0) {   
            // 0 = North, 1 = East, 2 = South, 3 = West
            myMonster.setFacing(3);
            myMonster.setIcon();
        }
   }

    public void keepClearing() {
        myMonster.isGridCleared();
    }

    public static void main(String args[]) {
        clearBlankGrid blankGrid = new clearBlankGrid();
        blankGrid.run();
    }
}

Upvotes: 3

duffymo
duffymo

Reputation: 308753

public class clearBlankGrid {

    // I made this static because you access it via a static method.  
    // If you make it a class member, as Greg Hewgill suggested, then 
    // change the method that uses it to be non-static
    private static  Monster myMonster = new Monster(10,10,5,5,1);


    public static void main(String args[]) {

        MonsterGUI myGUI = new MonsterGUI(myMonster);

        if (myMonster.getRows() > 0) {   
            // 0 = North, 1 = East, 2 = South, 3 = West
            myMonster.setFacing(3);
            myMonster.setIcon();
        }

    }

    public static void keepClearing() {

        myMonster.isGridCleared(); // Cannot find symbol 'myMonster'

    }
}

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 992937

Make myMonster a static class member:

public class clearBlankGrid {

    private static Monster myMonster;

    public static void main(String args[]) {

        myMonster = new Monster(10,10,5,5,1);
        // ...

    }
}

Upvotes: 1

SLaks
SLaks

Reputation: 887365

You need to put the object in a static field.

Upvotes: 1

Related Questions