首页 > 解决方案 > 初始化子类中的父变量

问题描述

这是我的父类

abstract public class Person {
private String name;
private Date birthday;
private double difficulty;

protected abstract String personType();
protected abstract Person clone();

Person(String name, Date birthday, double difficulty) {
    this.name = name;
    this.birthday = birthday;
    this.difficulty = difficulty;
}

Person(Person copy) {
    this.name = copy.name;
    this.birthday = copy.birthday;
    this.difficulty = copy.difficulty;
}
Person(){
    this.name = "";
    this.birthday = new Date();
    this.difficulty = 0;
}

public String getName() {
    return this.name;
}

public Date getBirthday() {
    return this.birthday;
}

public double getDifficulty() {
    return this.difficulty;
}

我想用相同的构造函数创建一个名为 Singer 的子类。我的问题是,如何通过调用父类 Person 来初始化 Singer 子类中的变量“name”、“birthday”和“difficulty”?

public class Singer extends Person{
String debutAlbum;
Date debutAlbumReleaseDate;

Singer(String name, Date birthday, double difficulty, String debutAlbum, Date debutAlbumReleaseDate){
    this.debutAlbum = debutAlbum;
    this.debutAlbumReleaseDate = debutAlbumReleaseDate;
    //im not sure what to put here for name, birthday, and difficulty
}   

}

标签: java

解决方案


您可以使用以下 3 个中的 1 个:

  1. 使用 super() 方法(推荐):在构造函数的第一行添加这一行super(name, birthday, difficult)。此行将Person为您的对象调用类的构造函数。 注意:super方法只能在构造函数的第一行使用
  2. 添加 set() 方法:在 Person 类中,为每个变量添加 set 方法,然后在构造函数中调用它们。
  3. 更改访问修改:将Person类中每个变量的访问修改更改为protectedorpublic然后使用this.name = name;.

推荐阅读