简体   繁体   中英

Using a non-static object in a static method

Okay, I can't figure out how to work this. When the object isn't static, none of the methods or variables used work, Java just won't compile them. However, when I make the object static, the JVM returns error, throwing a popup alert and spamming the console with error messages. Here's a severely cut down version of the broken code:

public class Main {

public Hero hero = new Hero();

private static boolean newGuy;

public static void main(String[] args){

    areYouNew();

    if(newGuy){
        createGame();
    }else{
        loadGame();
    }
    saveGame();

}

private static void createGame() {  

}

private static void loadGame() {

    System.out.println("Ah yes, sorry. What is your name again?");

    //blah blah code here

    hero.setName();


    if(hero.getName().length() > 0 ){

    }else{
        System.out.println("Sorry? You need to type your name");
        loadGame();
    }
}

private static void areYouNew() {

    System.out.println("Are you new?");

    String newTest = sc.nextLine();
    if(newTest.toLowerCase().contains("yes")){

        newGuy = true;

    }else if(newTest.toLowerCase().contains("no")){

        newGuy = false;

    }else{
        System.out.println("Oops, it's a yes or no question.");
        areYouNew();
    }
  } 
}

None of the hero.whatevers work unless I set hero to static. Any way to fix this? I already tried making the methods containing the references to hero non-static but then I can't use those methods in main()

The static part of a program is code that runs without using an instance of your Main class. When the main method is called, there is no instance of the Main class yet.

Normally, an object instance has certain fields. In your case there is only public Hero hero . Static fields, like private boolean newGuy are not part of the instance, but more like global variables. Since there is no object instance of Main yet, the hero field can't be accessed.

It is good practice to use object-oriented programming, in Java. You should probably create a new instance of your game as quickly as possible (using Main game = new Main() ). Then call methods on this instance ( game.createGame() , game.loadGame() ). Then, you don't need to make these methods static and you can access non-static fields. Also, this would allow you to have two Main instances at the same time, each with their own hero field, if such a thing would be needed at some point in your project.

You could, of course, also make the hero field static. It's a question of code style, I suppose.

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