2012-07-07 33 views
0

我有這個類:傳中,主要的類的對象科瑞到另一個類

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。我能怎麼做? 這是我想使用的類實例創建OtherClass對象之前

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

因此,基本上你正在運行2個應用程序,並且你想在它們之間傳遞數據?看看['Inter-process communication'](http://en.wikipedia.org/wiki/Inter-process_communication)。 – 2012-07-07 09:26:06

+0

@ Eng.Fouad是的。這是我想要做的......但我失敗了 – user1508419 2012-07-07 09:34:36

回答

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(); 
    } 
} 
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想要有兩個正在運行的應用程序,只需按照他的鏈接。

+0

不幸的是,你的解決方案對於我的案例研究來說並不舒適,因爲Object obj應該是Web服務器的一個支出。我無法兩次將Web服務器的實例 – user1508419 2012-07-07 09:36:02

+0

爲什麼你不能兩次? – Sajmon 2012-07-07 09:39:41

+0

因爲Object obj = new Object()在我的情況下是一個Web服務器的遺蹟。它已經在exxaple class中創建了。我不能再次將它傳遞給mymainmain,因爲它應該被創建兩次 – user1508419 2012-07-07 09:42:23

相關問題