Sourav Ganguly
Sourav Ganguly

Reputation: 329

How to create an object in main() that every other class can access? (Java)

So I want to use the same object that I used in my main method to be able to accessed by all other classes. How can I do this?

Upvotes: 0

Views: 1025

Answers (5)

xhassassin
xhassassin

Reputation: 283

You can't declare it in the main method. You have to declare it as a static variable under the class.

IE:

public class Temp
{
    public static String a = "";
    public static void main(String[] args)
    {
        a = "asdf";
    }
}

Now, you can access the variable a anywhere by calling Temp.a

Upvotes: 0

Leib Rozenblium
Leib Rozenblium

Reputation: 2409

You could also use a Singleton pattern which in the simplest (and thread-safe) form looks like

public class Single {
    private static final INSTANSE = new Single();
    //disallow instantiation outside
    private Single() {
    }
    public Single getInstance() {
         return INSTANCE;
    }
}

Upvotes: 0

minhaz1
minhaz1

Reputation: 743

You can make it static outside of the main method or you can pass it to the constructor of the other class.

Upvotes: 1

logoff
logoff

Reputation: 3446

The object must be declared outside main method as static. With this all the classes can access the same instance of the object, because it can only be one in the same JVM. Take a tour on the Oracle tutorials.

Upvotes: 4

SLaks
SLaks

Reputation: 887365

You should create a static field in any class.

Upvotes: 2

Related Questions