所以我試圖做到這一點,當用戶創建一個新的PlaceInformation對象時,輸入的經度和緯度被存儲在GeoLocation對象的地方。顯然,在運行「客戶端」代碼時,首先初始化GeoLocation對象,並賦予值0.0,0.0而不是用戶輸入的值。我該如何使GeoLocation對象中的構造函數存儲的緯度和經度參數?我嘗試了不同的方式,但有一些範圍問題。對象內的對象java
public class PlaceInformation {
private String name;
private String tag;
private String address;
private double latitude;
private double longitude;
GeoLocation place = new GeoLocation(latitude, longitude);
public PlaceInformation(String name, String address, String tag,
double latitude, double longitude) {
this.name = name;
this.address = address;
this.tag = tag;
this.latitude = latitude;
this.longitude = longitude;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getTag() {
return tag;
}
public String toString() {
return name + ", " + address;
}
public double test() {
return place.getLongitude();
}
public double distanceFrom(GeoLocation spot) {
return spot.distanceFrom(place);
}
}
好的,我明白了,我沒有意識到你可以在不提供參數的情況下實例化對象。所以實質上,直到用戶創建PlaceInformation對象,GeoLocation對象只是空白並等待被填充? – Nickomang
沒問題。直到您實例化GeoLocation對象並將其分配給位置之前,將點指向空引用。因爲'place'是一個實例變量,所以您不必擔心'NullPointerException',因爲類必須實例化才能使用。您可能考慮的另一件事是從PlaceInformation類中移除'latitute'和'longitude'字段,因爲這些值存儲在'place'中。 –
是的,我可以看到現在這些是多餘的。感謝您的幫助,我非常感謝快速回復! – Nickomang