Access static variable from a different class

1.5k views Asked by At

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?

2

There are 2 answers

0
DragonK On

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

}
0
ABHISHEK RANA On

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