简体   繁体   中英

Access static variable from a different class

So I have two classes:

A Main class with the public static void main(String args[]) method and a Voice class that accesses a static variable from that class.

Within the main class are methods that are used by itself, and are required to be static along with some of its variables.

So I have a static variable within the Main class (that's created/filled in the public static void main(String args[]) method. That's why this case is special) which the other class should be able to access.

Here is an example of what's happening:

public class Main(){

    public static int variable;

    /*
        Unrelated methods go here.
    */
    public static void main(String args[]){

        Voice v = new Voice();//This is just here for the code to make sense.
        variable = 5;

        v.doSomething();

    }
}

public class Voice(){

    public void doSomething(){
        System.out.println(Main.variable);
    }

}

Upon calling the doSomething() method in Voice , it leads to a nullPointerException .

I could fix this by passing on the variable variable to the Voice class, but is there a more easy way to fix this in the long run, if for instance, I needed to use more than one static variable from the Main class?

Your code is having syntax error. You can use this

class Main{

    public static int variable;

    /*
        Unrelated methods go here.
    */
    public static void main(String args[]){

        Voice v = new Voice();//This is just here for the code to make sense.
        variable = 5;

        v.doSomething();

    }
}

class Voice{

    public void doSomething(){
        System.out.println(Main.variable);
    }

}

Output will be 5

You should do as follows

public class Main{

    public static int variable;

    /*
        Unrelated methods go here.
    */
    public static void main(String args[]){

        Voice v = new Voice();//This is just here for the code to make sense.
        variable = 5;

        v.doSomething();

    }
}

 class Voice{

    public void doSomething(){
        System.out.println(Main.variable);
    }

}

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