简体   繁体   中英

Need to use instance in static and non-static methods

I'm making a little text game. The starting dialogue is in my main (static) method. From there, it sends you to other methods depending on your choices.

Now I think I need to have an instance of my class for this to work.

For example:

Program p = new Program();

if(stuff){
    p.room1();
}
else{
    p.room2();
}

Within those other methods there are global variables that will change.

So above the main method there is:

public bool hasItem = false;

So room1() would look like,

public void room1(){
    if(stuff){
        p.hasItem = true;
    } 
}

I know I'm screwing something up with the main method. Do I declare the instance "p" inside or outside of the main method? I've tried both but get errors both ways.

Edit: I ended up declaring a static "Program" outside of the main method to use elsewhere. Thanks for the help!

First off, you can either create a static Program outside of your main method, or declare a program inside your main method, depending on your architecture.

Second, you don't have to reference your instance from within your instance methods. Just use the field name. like so:

public void room1(){
    if(stuff){
        hasItem = true;
    } 
}

you can use this.hasItem if you want to be explicit about it.


Or better yet, make a brand new class to keep your state in. Having instance members in the class with the main method is awkward design.

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