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

Posted on 2009-04-18
Last Modified: 2012-05-06

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?

Question by:JamesFrog
    LVL 25

    Assisted Solution

    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
    LVL 92

    Accepted Solution

    > 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


    Author Closing Comment

    Thanks for clearing that up

    Featured Post

    How to improve team productivity

    Quip adds documents, spreadsheets, and tasklists to your Slack experience
    - Elevate ideas to Quip docs
    - Share Quip docs in Slack
    - Get notified of changes to your docs
    - Available on iOS/Android/Desktop/Web
    - Online/Offline

    Join & Write a Comment

    After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
    For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
    Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
    This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

    754 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now