user1508419
user1508419

Reputation: 333

pass an object creat in the main of a class to another class

I have this class:

public class Example
{
    public void static main(String[] args)
    {
        Object obj = new Object();
        OtherClass oc = new OtherClass(obj);
    }
}

public class OtherClass
{
    private Object object;
    public OtherClass(Object ob)
    {
    this.object = ob;
    }
}

Now I would use OtherClass in another main. how can i do? this is the class where I want to use OtherClass object created in the class Example before

public class myownmain
{
    public static void main(String[] args)
    {
        // Here I need OtherClass object created in Example class
    }
}

Upvotes: 0

Views: 487

Answers (3)

Simon Dorociak
Simon Dorociak

Reputation: 33495

You should have only one main(String[] args) method. If you want to pass OtherClass from Example class create method like

public static OtherClass getOtherClass(Object obj) {
   return new OtherClass(obj);
}

and then in MyOwnMain class just add

Object obj = new Object();
OtherClass oc = Example.getOtherClass(obj);

But as meant @Eng.Fouad if you want to have two running apps, just follow his link.

Upvotes: 1

buc
buc

Reputation: 6358

A Java program usually has only one main method, or to be more specific, only one main method will be called when your program starts. However, it is possible to call the other main method from yours.

You cannot do this without restructuring the Example class above, because the OtherClass instance is a local variable in the main method, thus you cannot retrieve it.

One solution would be to instantiate the OtherClass in your own main method:

public class myownmain {
    public static void main(String[] args) {
        Object obj = new Object();
        OtherClass oc = new OtherClass(obj);
    }
}

The other option is to rewrite the Example class to expose the OtherClass instance as a static attribute:

public class Example {
    private static OtherClass oc;

    public static OtherClass getOc() {
        return oc;
    }

    public static void main(String[] args) {
        Object obj = new Object();
        oc = new OtherClass(obj);
    }
}

Then you can get this instance after calling Example.main:

public class myownmain {
    public static void main(String[] args) {
        Example.main(args);
        OtherClass oc = Example.getOc();
    }
}

Upvotes: 1

Jari
Jari

Reputation: 2152

The main functions in those different classes represent different applications and you won't be able to refer to objects created in one application from another.

In case you want to use similar objects in the other main function you simply have to create new instances and use those instead. It is not obvious though what you are trying achieve.

Upvotes: 1

Related Questions