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

标签 java inheritance constructor subclass

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

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/

相关文章:

java - 代码约定 - 捕获异常而不是之前进行 if-checking 的好习惯还是坏习惯?

c++ - std::make_shared 在 VS2012 中进行两次构造函数调用

C++异常继承歧义

C++如何优雅地处理不被继承的友情

java - 使用 Java 中的组合和接口(interface)进行设计

c++ - 什么时候调用继承的Constructor代码

c++ - 双重自由或腐败(出)C++

java - 为什么在Gradle war插件中 'javax.servlet'可以是 'ProvidedCompile'?

java - 如何使用 Hibernate 检索集合的特定成员?

java - 自动化屏幕分辨率