2015-04-04 40 views
0
public perform Ulti (Location origin, int number) { 

     Map i = new Map(origin, i.getDestination(), number); 

} 

Map的構造函數是(Location n,Location m,int k);(JAVA)在一行中初始化對象 - 調用方法

我的問題是,我不知道目的地,但在Map中有一個名爲getDestination()的方法。我知道的來源是第一個參數,我怎樣才能使用新創建的對象的方法?

注意:地圖對象不能爲空; //所以我不確定什麼其他的佔位符我可能會使用

+1

這可不行,因爲我地圖是不是初始化。 無論如何,如果你有一個方法在我,爲了得到目的地,爲什麼你需要通過目的地我作爲參數?你不能只在像this.getDestination()這樣的Map構造函數中調用getDestination()? – 2015-04-04 02:48:36

+0

所以你的'Map'是一個具體的類? – Razib 2015-04-04 02:56:39

+0

(這不能工作,因爲'我'還沒有在範圍內......不用擔心它沒有被初始化;這會導致像「*無法找到符號* ..變量i」的錯誤。) – user2864740 2015-04-04 03:25:47

回答

0

如果你有保存目的地的變量,所以你必須將其設置第一

例如:

map i = new map(); 
i.setDistination("----"); 
String distination = i.getDistination(); 

,但在你的榜樣你可以簡單地鍵入一個目的地或從其他對象獲取它。

+0

這不會工作地圖有3個參數。 (來源,目的地,號碼)。 我不需要設置目的地,目的地是在Map類中預定義的。我需要獲取目標作爲對象的參數。 – noobatrilla 2015-04-04 03:22:05

+0

如果目的地尚未設置,那麼你想返回什麼! 一個例子:你可以使一個構造函數不接收目的地,找到目的地然後得到目的地 – 2015-04-04 03:34:43

+0

啊我看到了,謝謝你生病了試試。 – noobatrilla 2015-04-04 03:36:55

0

如果不創建對象的方法,則無法調用。如果可以的話,傳遞對象本身已有的值是沒有意義的。什麼是目的地?如果您有其他方式訪問它,只需向Map添加一個空的構造函數。 像這樣

public class Map{ 
    public Map(){ 

    } 
    //Rest of code 
} 

現在你可以創建一個沒有目標對象: 地圖I =新地圖(); ,然後設置目的地後,你有它。

1

你可以做以下的事情你Map類中 -

class Map{ 

    Location origin; 
    Location destination; 
    int number; 

    //create a no argument constructor so that your Map can 
    // be created without any constructor whenever required 
    Map(){ 

    } 

    //create a constructor with two argument 
    Map(Location origin, int number){ 
     this.origin = origin; 
     this.number = number; 
    } 


    //getter and setter methods. 

} 

現在你可以創建Map實例/對象這樣的 -

Map i = new Map(origin, number); 
Location m = // some code for generating Location as destination 
i.setDestination(m); 
+0

謝謝,我不知道你可以創建一個空的構造函數。似乎看起來不錯。再次感謝。 – noobatrilla 2015-04-04 03:45:19