Java构造函数不在同一个包中工作

Java构造函数不在同一个包中工作,java,Java,一个简单的例子: 我试图使用构造函数创建对象,但我的对象被创建为空。构造函数位于同一个包中的不同类中 public static void main(String[] args) { //Initialize all data: ArrayList<Airport_example> all_airports = new ArrayList<Airport_example>(); Airport_example perth = new Airp

一个简单的例子:

我试图使用构造函数创建对象,但我的对象被创建为空。构造函数位于同一个包中的不同类中

public static void main(String[] args) {

    //Initialize all data:
    ArrayList<Airport_example> all_airports = new ArrayList<Airport_example>(); 

    Airport_example perth = new Airport_example("01","Perth","PER","Australia","WST");
    Airport_example brisbane = new Airport_example("02","Brisbane","BNE","Australia","EST");

    //Add airports to ArrayList
    all_airports.add(perth);
    all_airports.add(brisbane);

            //debugging
    System.out.println(all_airports);
}   

你的构造器工作得很好;问题是您正在扩展一个
HashMap
,并希望它知道
Airport\u示例
子类的私有字段的内容。要使打印语句按预期工作,必须重写该方法

我建议您将代码更改为以下内容:

public class Airport_example {

private String airportID;
private String city;
private String code3;
private String country;
private String timezone;

public Airport_example(String airportID, String city, String code3, String country, String timezone) {
    this.airportID = airportID;
    this.city = city;
    this.code3 = code3;
    this.country = country;
    this.timezone = timezone;
    }
}

public String toString() {
    // replace the string you want each object to print out
    return this.airportID + ", " + this.city + ", " + this.code3 + ", " + this.country + ", " + this.timezone;
}

它打印空数组的原因是,它当前正在调用
HashMap
toString
,并且,由于您没有定义任何
HashMap
字段,它将其视为空的
HashMap

为什么期望
HashMap.toString()
了解
机场的私有字段\u示例
?此外,为什么首先要扩展
HashMap
?为什么要扩展HashMap?顺便说一句,构造函数工作得很好…诀窍是你需要在airport类中重载
toString
。但正如其他人所指出的,扩展
HashMap
可能是个坏主意。(从什么时候开始,“airport”需要充当通用名称-值映射?我觉得这有点不正确的OO建模。)另一个问题是,您对类名的选择很差。1) 您正在为“机场”建模,而不是“机场示例”。2) 类名违反了Java标识符约定。
[{}, {}]
public class Airport_example {

private String airportID;
private String city;
private String code3;
private String country;
private String timezone;

public Airport_example(String airportID, String city, String code3, String country, String timezone) {
    this.airportID = airportID;
    this.city = city;
    this.code3 = code3;
    this.country = country;
    this.timezone = timezone;
    }
}

public String toString() {
    // replace the string you want each object to print out
    return this.airportID + ", " + this.city + ", " + this.code3 + ", " + this.country + ", " + this.timezone;
}