Java, making a variable accessible from all methods in all package

Hi,

I have a program with a main method, and lots of classes in different packages (all containing various methods).

Is there a way that I can declare a variable in the main method, which can then by used my any method, in any class, in any package?

Thanks
J
JamesFrogAsked:
Who is Participating?
 
objectsConnect With a Mentor Commented:
> Is there a way that I can declare a variable in the main method, which can then by used my any method, in any class, in any package?

no, it would need to be a member variable, possibly a class member var if the other classes don't have access to an instance of that class

0
 
InteractiveMindConnect With a Mentor Commented:
You'll have to declare the variable static in your class, so something like:

public class myMainClass
{
    public static DataType variableName;
   
    . . .

    public static void main(String[]a)
    {
          . . .
          variableName = new DataType(blah blah);
          . . .
     }
}

Then in your other methods, you can access it by calling myMainClass.variableName
0
 
JamesFrogAuthor Commented:
Thanks for clearing that up
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.