2012-02-25 104 views
1
public final class City 
{ 
public final long id; 

public final String name; 

public final double latitude; 

public final double longitude; 

public City(long id, String name, double lat, double lng) 
{ 
    this.id = id; 
    this.name = name; 
    this.latitude = lat; 
    this.longitude = lng; 
} 

public static City fromJsonObject(JSONObject json) throws JSONException 
{ 
    return new City(json.getLong(WebApi.Params.CITY_ID), 
      json.getString(WebApi.Params.CITY_NAME), 
      json.getDouble(WebApi.Params.LATITUDE), 
      json.getDouble(WebApi.Params.LONGITUDE)); 
} 
} 

這是我的班。我想在另一個類中訪問這個類的值;我怎麼做? (緯度,經度,cityid和城市名的值)如何爲只有參數化構造函數的類創建對象?

+0

您還沒有初始化你的最終變數。你的代碼如何被編譯? – 2012-02-25 08:21:23

+0

@ShashankKadne你認爲總決賽沒有初始化的地方?或者,也許OP在你的問題後編輯了他的構造函數? – 2012-02-25 09:09:08

回答

3

這可以通過使用instance.member符號來進行:(這就像調用方法,只是沒了括號;-)

City c = City.fromJsonObject(...); 
system.out.println("City name: " + c.name); // etc. 

因爲成員標記爲final它們必須在構造函數中聲明爲時設置。在這種情況下,它們被設置在從工廠(靜態)方法調用的構造函數中。然而,因爲他們是最終的,這將是無效的:

City c = ...; 
c.name = "Paulville"; // oops (won't compile)! can't assign to final member 

雖然有些人可能認爲到[總是]用「干將」,因爲這是一個[簡單] 不可變對象,我覺得它(直接成員訪問)一個有效的方法。然而,關於「getters」的一個真正好處是它們可以在接口中定義,因爲它們實際上只是方法。這個方便的功能可以以後會有用,以避免ABI的最新變化,或使DI,或允許嘲諷......但不要過度設計:)

(我一般避免「二傳手」,除非絕對需要......不需要引入可變狀態,如果需要改變狀態,我想通過「動作」來改變它。)

快樂編碼。現在


,假設這個問題是關於刪除靜態工廠方法,同時仍然保持最後的成員,那麼它仍然可以平凡完成(但是,那麼這引入了「構造函數可以拋出異常」)這是一個完全不同的蠕蟲......無論如何,請注意,分配給構造函數中最終成員的要求仍然是滿員的。

// constructors can (ickickly) throw exceptions ... 
public City(JSONObject json) throws JSONException 
{ 
    id = json.getLong(WebApi.Params.CITY_ID), 
    name = json.getString(WebApi.Params.CITY_NAME), 
    latitude = json.getDouble(WebApi.Params.LATITUDE), 
    longitude = json.getDouble(WebApi.Params.LONGITUDE)); 
} 

也許它希望保持/利用工廠方法,同時還提供一個構造函數重載,但是這是真的開始變得愚蠢 ...

public City(JSONObject json) throws JSONException 
    : this(City.fromJsonObject(json)) { 
    // we do everything in the next constructor, it would be neat if it 
    // was possible to do static/local stuff before calling the base constructor 
    // (so that we could pass in multiple arguments, but .. not possible in Java) 
} 

City(City other) { 
    // a "copy constructor" 
    // just copy over the member values, note no exception from here :) 
    // also note that this fulfills the contract of assigning to the final 
    // members when used as the base constructor for City(JSONObject) 
    id = other.id; 
    name = other.name; 
    latitude = other.latitude; 
    longitude = other.longitude; 
} 
+0

當我從另一個類訪問變量時,我正在獲取java.nullpoint異常。我只是想使用值。不想修改它們。 – Maddy 2012-02-27 04:35:38

+0

@Maddy也許'null'是分配的值(到'name',其他字段不能爲null,因爲它們是基本類型)?也就是說,getString'可以返回null嗎?或者它可能跟這個班沒有關係? – 2012-02-27 07:34:30

相關問題