2014-11-08 32 views
1

我正努力尋找如何通過另一種靜態方法發送/訪問已在主要方法中創建的對象。如何訪問在主要方法中創建的對象

這裏是我的我的一些服務類的代碼,它由公共構造函數,訪問和mutator方法:

public class Participants 
    { 
     String firstName=" "; 
     String lastName=" "; 
     int socialSecurity=0; 
     int ticket=0; 

     char status='N'; 
     Vehicle veh=null; 


     public Participants(String fn, String ln, int ssn, int tkt) 
     { 
      firstName=fn; 
      lastName=ln; 
      socialSecurity=ssn; 
      ticket=tkt; 
     } 
    } 

還有就是客戶端類,它有在那裏我創建和初始化的主要方法對象和第二方法,我試圖訪問這些對象:

public class Race 
{ 
    public static void main(String[] args) 
    { 
     .... 
     Participants []people=new Participants[35]; 
     Vehicle []cars=new Vehicle[10]; 
...code to "fill" those objects 
     GiveAway([]cars,[]people); //sending those objects to static method- doesn't work from here) 
    } 

public static void GiveAway(Vehicle[] veh, Participants[] part) 
    { 
     //set of instructions to work and change those objects 
    } 
} 

的代碼根本不工作,那是因爲我真的不知道如何可以「送」的對象數組的方法(順便說一下,這可能嗎?)。

我正確的做法嗎?或者有更簡單的方法?我發現了一些關於私人課程和其他一些內容的主題,但無法弄清楚如何處理我的代碼。

我很感謝任何幫助

謝謝!

回答

2

我認爲你認爲數組名稱是[]people[]cars。不是。當你聲明它們,它實際上是:

Vehicle[] cars = new Vehicle[10]; 
└───────┘ └──┘ 
    Type  var name 

所以數組被命名爲cars,這就是你應該如何將它傳遞給另一種方法:

GiveAway(cars, people); 

補充說明:不給方法名稱以大寫字母開頭。慣例是隻有類型名稱(類,接口等)以大寫字母開頭。常量是全部大寫的,並且方法的首字母小寫。

1

您對GiveAway通話應該是這樣的

GiveAway(cars, people); 

這些括號是給你一個編譯器錯誤。

1
Participants []people=new Participants[35]; 
Vehicle []cars=new Vehicle[10]; 
GiveAway([]cars,[]people); 

應該是

Participants[] people=new Participants[35]; 
Vehicle[] cars=new Vehicle[10]; 
GiveAway(cars, people); 

在Java使用[]到信號編譯器,這是一個數組。你把它放在要創建一個數組(參與者,車輛)的對象的名字後面。當調用「GiveAway」時,您只需要使用數組的名稱。

相關問題