這可以通過使用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;
}
您還沒有初始化你的最終變數。你的代碼如何被編譯? – 2012-02-25 08:21:23
@ShashankKadne你認爲總決賽沒有初始化的地方?或者,也許OP在你的問題後編輯了他的構造函數? – 2012-02-25 09:09:08