Take the 2-minute tour ×

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. The simplified main class looks like this

    public static void main (String[] args)
    MyMain x = new MyMain ();

    public void change()


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?

share|improve this question

3 Answers 3

up vote 2 down vote accepted

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() { ...
share|improve this answer
Thank you, the second option worked. –  Damokles Jul 13 '11 at 17:13

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

share|improve this answer

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

share|improve this answer

Your Answer


