将类主体中的对象creat传递给另一个类

时间:2012-07-07 09:18:45

标签: java

我有这堂课:

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;
    }
}

现在我将在另一个主要使用OtherClass。我能怎么做? 这是我想在

之前的类Example中创建的OtherClass对象的类
public class myownmain
{
    public static void main(String[] args)
    {
        // Here I need OtherClass object created in Example class
    }
}

3 个答案:

答案 0 :(得分:1)

这些不同类中的主要功能代表不同的应用程序,您将无法引用另一个应用程序中创建的对象。

如果您想在其他主要功能中使用类似对象,您只需创建新实例并使用它们。虽然你想要实现的目标并不明显。

答案 1 :(得分:1)

Java程序通常只有一个main方法,或者更具体一点,程序启动时只会调用一个main方法。但是,可以从您的方法中调用其他main方法。

如果不重构上面的Example类,则无法执行此操作,因为OtherClass实例是main方法中的局部变量,因此您无法检索它。

一种解决方案是在您自己的OtherClass方法中实例化main

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

另一个选项是重写Example类以将OtherClass实例公开为静态属性:

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);
    }
}

然后,您可以在调用Example.main后获取此实例:

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

答案 2 :(得分:1)

您应该只有一个main(String[] args)方法。如果你想从示例类创建方法传递 OtherClass

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

然后在 MyOwnMain类中添加

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

但是,如果你想拥有两个正在运行的应用,那么就像 @ Eng.Fouad 一样,只需按照他的链接即可。