Bruce Wayne Bruce Wayne - 6 months ago 10
Java Question

How to acces local variables in another class

I am making a program that needs a variable from the main method, but when I try to import it by using

Main main = new Main();
I Can't access the variable. How can I use the variable a in another class?

public class Main{
public static void main(String[] args){
int a = 10;
}
}

public class SomeClass{
Main mainclass = new Main();
main.a;//I get errors when I do this
}

Answer

That is why it is called a "local" variable. It is only available locally in the scope it is defined in and you can in no way whatsoever access this variable unless you add some native code and mess with some dirty pointers.

If you need a in another class and from the static main method you need to make a a static member of the class, pulling it outside the local scope like

public class Main{
    static int a;
    public static void main(String[] args){
        a = 10;
    }  
}

public class SomeClass{
    Main.a;
}

But actually I think you should get a good book about Java and about object oriented development before you proceed, because your example shows that you have not many clues about both of them.

Comments