[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 402
  • Last Modified:

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
0
JamesFrog
Asked:
JamesFrog
2 Solutions
 
InteractiveMindCommented:
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
 
objectsCommented:
> 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
 
JamesFrogAuthor Commented:
Thanks for clearing that up
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now