How to make the scope of an instance of a Main class exist through the whole class
Is it possible to make the scope of an instance of a main class exist through the whole main class? I am trying to run methods from my object classes, but the methods are in the main class. Th开发者_如何学Pythone simplified main class looks like this
public static void main (String[] args)
{
MyMain x = new MyMain ();
}
public void change()
{
System.out.println("whatever");
}
MyMain()
{
System.out.println("--1--");
}
Now if I wanted to call the method public void change from the object, I would normally just use x.change(); or MyMain.x.change; in the object, but the scope of x is obviously not reaching the object. Is there a way make the scope bigger for the object while only saying MyMain x = new MyMain(); once?
Make x a static variable:
private static MyMain x = new MyMain();
or make the change function static, so you don't need an instance to call it:
public static void change() { ...
I would pass main object as dependency to other objects. Or better segregate an interface (something like IChangeable) and pass it instead of actual object.
As a workaround you could make main object a Singleton
You have to options for growing the scope. Either you pass a refernce to MyMain into every object that should call a method from there, or you add a static variable holding your MyMain.
The first approach could be easily done because probably it creates all other objects. So it would be easy to write new Foo(this)
instead of new Foo()
. This is called Inversion of Control.
The other method would in-fact introduce a global variable. This pattern is called singleton-pattern. Look here for an implementation: (first hit from google) http://radio-weblogs.com/0122027/stories/2003/10/20/implementingTheSingletonPatternInJava.html
精彩评论