gpt4 book ai didi

java - Java 中的继承和构造函数

转载 作者:行者123 更新时间:2023-12-01 17:28:48 27 4
gpt4 key购买 nike

所以,我正在做一项家庭作业,但我很难遵循一些指示,我已将作业粘贴在下面:

Create a hierarchy of five classes, plus one class included as a variable inside:

  1. Person has four String variables: name, address, phone, email
  2. Student is a subclass to Person and has one additional int variable status which takes values of 1, 2, 3, or 4 representing freshman, sophomore, junior, senior
  3. MyDate has three int variables for year, month, and day
  4. Employee is a subclass to Person and has one String variable office, one int variable for salary, and one MyDate variable for dateHired
  5. Staff is a subclass to Employee and has one additional String variable for title
  6. Faculty is a subclass to Employee and has one additional String variable for rank which takes values of Professor, Associate Professor, Assistant Professor, Instructor, and Adjunct. The data for all six classes should be private.

As for methods, you can skip the normal setters and getters if you write a single constructor that has parameters for all data and override the toString( ) method. Constructors of subclasses should use the super class constructor. The toString( ) methods of subclasses should use the toString( ) method of their super class.

让我陷入困境的部分是这样的想法:可以编写一个构造函数来涵盖 setter 和 getter 的所有必要参数,而不是将它们编写在每个子类中。这可能吗?怎么会这样呢?

最佳答案

创建子类时需要使用父类(super class)的构造函数。所以应该是:

public class Staff extends Employee {    

private String title;

public Staff(String name, String address, String phone, String email, int status, String title) {
super(name, address, phone, email, status);
this.title = title;
}
}

使用super(/*父类(super class)的params*/)调用父类(super class)的构造函数并实例化继承的属性。请注意,您只能将父类(super class)构造函数作为构造函数的第一条语句进行调用。如果您没有显式调用父类(super class)构造函数,Java 编译器会自动插入对 super()(父类(super class)的默认构造函数)的调用。

要调用父类的 toString(),请使用:

public String toString() {
return super.toString() + " ,title : " this.title;
}

类似地编写所有类的构造函数和toString()方法。

关于java - Java 中的继承和构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12967395/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com