【发布时间】:2018-02-28 15:25:10
【问题描述】:
前几天我遇到了一个奇怪的情况。这里是:
我有一个抽象类和一个扩展它的子类。抽象类有一个无参数构造函数来初始化地图,但就是这样。
子类没有我明确编写的任何构造函数,一切正常。
然后有一天,我在子类中添加了一个自定义构造函数,其中包含一组用于单元测试的参数。然而,这破坏了我的主程序,因为其父类中的地图始终为空。
为了解决这个问题,我在完全空白的子类中放置了另一个构造函数(没有参数或任何东西)。出于某种原因,这确保了超类构造函数将被调用并且不会抛出空指针异常。为什么之前没有被调用,为什么现在可以工作?
子类:
public class BillToSite extends XWStoreRequestDataElement {
private String country;
private String state;
private String county;
private String city;
private String zip;
private String address;
public BillToSite() { } //WHY DOES THIS FIX IT???
//Only used for unit test.
public BillToSite(String address, String city, String state, String zip, String county, String country){
this.address = address;
this.city = city;
this.state = state;
this.zip = zip;
this.county = county;
this.country = country;
}
抽象类:
public abstract class XWStoreRequestDataElement {
private Map<String, String> attributes;
public XWStoreRequestDataElement(){
attributes = new HashMap<>();
}
【问题讨论】:
标签: java inheritance constructor