Java构造函数无法在同一包中使用

曼陀罗

一个简单的:

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

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);
}   

单独类中的构造函数如下所示:

public class Airport_example extends HashMap<String,String> {

//list of variables

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

// constructor to initialize objects
public Airport_example(String airportID, String city, String code3, String country, String timezone) {
    // Constructor variable initialization
    this.airportID = airportID;
    this.city = city;
    this.code3 = code3;
    this.country = country;
    this.timezone = timezone;

}

}

System.out.println语句返回一个空数组。我错过了一个简单的把戏吗?

[{}, {}]
阿内什·阿舒托什(Aneesh Ashutosh)

您的构造函数工作正常;问题是您正在扩展aHashMap并期望它知道Airport_example子类的私有字段的内容要使打印语句按预期方式工作,必须重写该toString方法。

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

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;
}

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

同一包中的两个Java文件,但仍然出现错误,找不到符号:class(使用intellij IDE)

从同一包中读取文件

无法在Java中使用构造函数

使用pytest时在同一包中导入的ModuleNotFoundError

在Java中,为什么可以从同一包中的类外部访问受保护的成员?

无法从不同jar中的同一包访问父类的受保护成员

为什么有些Java代码再次导入同一包?

Java新手问题:同一包的类相互访问?

转:同一包中的未定义函数

同一包中的功能可见性

无法在同一包中单独编译所有类

如何在同一包中的另一个类中使用一个类?

@SpringBootApplication在同一包中?

为什么同一包的一类无法访问另一包?

Java导入类在同一包中

IntelliJ编译时无法在同一包中找到类

在包__init__内修补函数,并在同一包内的模块内使用它

如何预加载共享库并使用在同一包装函数中使用malloc的函数包装malloc?

为什么Java类可以在不显式导入该类的情况下直接在同一包下使用另一个类?

React Hook无法在同一函数中使用新状态

同一包-多个存储库

R如何在同一包中使用文件

Java-如何从同一包中的类获取私有数据

如何在同一包中的当前Java文件中使用其他Java文件的变量?

如何在JAVA的同一包中调用方法或访问其他类中的字段

Chocolatey允许并排使用同一包装的多个版本吗?

java ant compile在同一包中的同一目录中找不到类

在 Scala 中使用同一包上的特征中定义的类。

从同一包中的过程返回特定事物的函数