简体   繁体   中英

how to use instance variables in a static method

I have a problem going on in Java.
I'm really new to Java, so don't blame me for weird code and stuff.

I'm making a small thingymabob that randomly generates numbers and uses them to create information about a randomly generated tree that is outlined by that information.
The problem is, I need to make a static void to print the stats of the tree.

But all my variables - "treeheight", "treetrunkwidth", etc. - can't be static, or every variable piece of information reverts to 0 or null. And this is annoying, because if I make my void for printing the tree stats not static, then it doesn't show up, but if I make it static, it won't let the tree's information be randomly generated and changed at will.

What do I do??

-AndeX

as simple as that

1 : static members can be accessed with class reference

ClassName.staticVar

2 : non static members can be accessed by instance reference

new CLassName()

now if you can please post your code , we can give exact suggestion

Inside Thingymabob you can create

public static void main(String[] argsIgnored) {
    Thingymabob anInstance = new Thingymabob();
    anInstance.doStuffToSetItUp()...
    System.out.println("treeheight = " + anInstance.getTreeheight ());
    System.out.println("treetrunkwidth = " + anInstance.getTreetrunkwidth ());
    etc...
}

I think what you are looking for is the Java Singleton Class . I recommend you look here for more information

It will mean that you will only ever have one instance of you class Thingymabob and you can access its properties as you normally would via getters and setters .

This is what the constructor and getInstance would look like:

private Thingymabob() {
    // Exists only to defeat instantiation.
}

public static Thingymabob getInstance() {
    if(instance == null) {
        instance = new Thingymabob();
    }
    return instance;
}

You would then access it in all your other classes like so:

Thingymabob thingy = Thingymabob.getInstance();

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