java - 使用包含另一个类作为属性的对象的构造函数

标签 java

我正在尝试测试我的类(class) Location使用另外两个类作为属性 AddressGeolocation但是,当从 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/

相关文章:

Java 9 弃用 SHA1 证书,还是其他问题?

java - android和javafx轻量级兼容事件框架

java - 从文本字段中提取空数据。表已填充,但无法检索对象。 Java/JavaFX

java - 如何使用带有 DatagramChannel 的 Selector 对象进行非阻塞数据包接收

java - 将 javascript 日期传递给 java

java - 来自数据库的 Vertx shiro 身份验证

java - JPA 实体及其自定义功能

java - Java 中增强的 for 循环和迭代器

支持 DTD 的 Java ValidationAPI 库

java - 所有不可变对象(immutable对象)都可以重用吗?