簡體   English   中英

(JAVA)初始化對象-一行調用方法

[英](JAVA) Initializing object - calling method in one line

public perform Ulti (Location origin, int number) { 

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

} 

Map的構造函數為(Location n,Location m,int k);

我的問題是,我不知道目的地,但是Map中有一個名為getDestination()的方法。 我知道將原點輸入第一個參數 ,如何使用新創建對象的方法?

注意:Map對象不能為null; //所以我不確定我還可以使用其他占位符

如果您擁有用於保存目的地的變量,則必須先進行設置

例如 :

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

但在您的示例中,您只需鍵入目標或從其他對象獲取它即可。

您可以在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);

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

public class Map{
     public Map(){

     }
     //Rest of code
}

現在,您可以創建沒有目標的對象:Map i = new Map(); 然后設置目的地。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM