简体   繁体   中英

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'

    }

}

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();
    }
}

您需要将对象放在静态字段中。

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);
        // ...

    }
}
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'

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM