我正在尝试测试我的类(class) Location
使用另外两个类作为属性 Address
和Geolocation
但是,当从 main 构造对象时,我收到指针错误。
这就是我的主要部分
import java.util.ArrayList;
public class LocationTest {
public static void main(String[] args) {
ArrayList<Location> locationList = new ArrayList<>();
locationList.add(new Location(new Address(1, "Abubakr rd Almorsalat", "Riyadh", "Saudi Arabia"), new Geolocation(24.7136, 46.6753, 612), 1, "Prince Sultan University"));
locationList.add(new Location(new Address(1, "Nassria st", "Sfax", "Tunisia"), new Geolocation(34.7478, 10.7662, 20), 2, "Second Location"));
locationList.get(1).getGeolocation().setAltitude(20);
locationList.get(0).getAddress().setStreetNumber(15);
for(Location i : locationList) {
System.out.println(i.getGeolocation());
}
}
}
我在 Location
中使用的两个类都有 getter 和 setter这是他们的设置方法
public void setAddress(Address address) {
this.address.setStreetNumber(address.getStreetNumber());
this.address.setStreetName(address.getStreetName());
this.address.setCity(address.getCity());
this.address.setCountry(address.getCountry());
}
public void setGeolocation(Geolocation geolocation) {
this.geolocation.setLatitude(geolocation.getLatitude());
this.geolocation.setLongitude(geolocation.getLongitude());
this.geolocation.setAltitude(geolocation.getAltitude());
}
我感觉问题就在这里,但我不确定
错误是
Exception in thread "main" java.lang.NullPointerException
at quiz01.fall2016.Location.setAddress(Location.java:59)
at quiz01.fall2016.Location.<init>(Location.java:20)
at quiz01.fall2016.LocationTest.main(LocationTest.java:13)
构造函数
public Location(Address address, Geolocation geolocation, int id, String name) {
setAddress(address);
setGeolocation(geolocation);
setId(id);
setName(name);
}
最佳答案
在 setAddress
调用 this.address
上的 setter 之前,请确保正在初始化 this.address
。
默认情况下,所有对象都将使用 null
进行初始化,因此您将遇到 NullPointerException。
您的构造函数应如下所示
public Location(Address address, Geolocation geolocation, int id, String name) {
// Initialize objects.
this.address = new Address();
this.geolocation = new Geolocation();
setAddress(address);
setGeolocation(geolocation);
setId(id);
setName(name);
}
关于java - 使用包含另一个类作为属性的对象的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48681234/