所以我试图做到这一点,以便当用户创建一个新的 PlaceInformation 对象时,输入的纬度和经度存储在 GeoLocation 对象位置内。显然,在运行“客户端”代码时,GeoLocation 对象首先被初始化并被赋予值 0.0, 0.0 而不是用户输入的值。如何使构造函数中的纬度和经度参数存储在 GeoLocation 对象中?我尝试了一种不同的方式,但存在一些范围问题。
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);
}
}
最佳答案
在构造函数中实例化对象。
public class PlaceInformation {
private String name;
private String tag;
private String address;
private double latitude;
private double longitude;
GeoLocation place;
public PlaceInformation(String name, String address, String tag,
double latitude, double longitude) {
place = new GeoLocation(latitude, longitude);
this.name = name;
this.address = address;
this.tag = tag;
this.latitude = latitude;
this.longitude = longitude;
}
/* Rest of class omitted */
}
另请注意,您可能希望将地点
设为私有(private)。
关于java - 对象中的对象 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20230515/