java - 初始化子类中的父变量
问题描述
这是我的父类
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
}
}
解决方案
您可以使用以下 3 个中的 1 个:
- 使用 super() 方法(推荐):在构造函数的第一行添加这一行
super(name, birthday, difficult)
。此行将Person
为您的对象调用类的构造函数。 注意:super方法只能在构造函数的第一行使用 - 添加 set() 方法:在 Person 类中,为每个变量添加 set 方法,然后在构造函数中调用它们。
- 更改访问修改:将
Person
类中每个变量的访问修改更改为protected
orpublic
然后使用this.name = name;
.
推荐阅读
- r - 使用 rvest 抓取 df 列中的链接
- javascript - 如何通过 Javascript 在屏幕上显示前 20 个单词,然后显示下 20 个单词?
- c# - 如何将输入中的每个单词与列表进行比较并返回布尔值
- sql - 对 Group By Condition 下的结果求和
- python - 如果稍后在 python (pandas) 中出现相同的值,则为虚拟
- javascript - 无法在 Jquery ajax 上发布数据
- java - XStream:不能同时反序列化属性和隐式集合
- php - 如何显示 PHP-cURL 错误?
- laravel - 没有收到任何错误,但数据未存储在数据库 laravel 8 中
- php - Yii2 Restful API 无效凭证