Reputation: 329
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
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
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
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
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