如何在扩展类中创建构造函数

时间:2019-03-28 01:04:51

标签: java

我尝试在扩展类中创建构造函数,以便在主类中创建对象。当我生成默认的eclipse构造函数时,它显示了我超类的所有字段,并且当我尝试在主类中创建对象时,我需要放置所有字段。

这是我的Person类:

public class Person {
private String id;
private String name;
private String gender;
private String country;
private String cities;
private String birthDate;
private String deathDate;
private List<String> aliases = new ArrayList<String>();
private List<String> tags = new ArrayList<String>();

public Person(String id, String name, String gender, String country, String cities, String birthDate,
        String deathDate, List<String> aliases, List<String> tags) {

    this.id = id;
    this.name = name;
    this.gender = gender;
    this.country = country;
    this.cities = cities;
    this.birthDate = birthDate;
    this.deathDate = deathDate;
    this.aliases = aliases;
    this.tags = tags;
}

这是我扩展的小组课:

public class Group extends Person{
private String name;
private String country;
private String cities;
private String beginDate;
private String endDate;
private List<String> aliases = new ArrayList<String>();
private List<String> tags = new ArrayList<String>();
private List<Person> members = new ArrayList<Person>();

public Group(String id, String name, String gender, String country, String cities, String birthDate,
        String deathDate, List<String> aliases, List<String> tags, String name2, String country2, String cities2,
        String beginDate, String endDate, List<String> aliases2, List<String> tags2, List<Person> members) {
    super(id, name, gender, country, cities, birthDate, deathDate, aliases, tags);
    name = name2;
    country = country2;
    cities = cities2;
    this.beginDate = beginDate;
    this.endDate = endDate;
    aliases = aliases2;
    tags = tags2;
    this.members = members;
}

这是生成的构造函数(巨大的) 当我尝试在主对象上创建对象时,它需要所有字段(甚至是Person的class字段) 那么,有什么方法可以通过仅填充我的Group类的字段来创建Group对象?预先感谢。

2 个答案:

答案 0 :(得分:0)

public class Group extends Person {

当您写Group extends Person时,表示一个小组是一种人。但这是不对的。一组包含个人;它本身不是一个人。不要使用继承,而要使用成员身份。您已经有了List<Person> members,因此实际上要摆脱extends子句。

答案 1 :(得分:0)

我认为您应该能够创建一个较小的构造函数,并为

中的字段写空值
super (...)

未定义

public Group(String id, String name, String gender) {
    super(id, name, gender, null, null, null, null, null, null);
}

像这样

PS注意超类中的nullPointer异常