我有3个班级:管理员,带薪雇员和雇员。管理员从受薪雇员中扩展而来,从雇员中扩展。这是它们的默认构造函数:
雇员:
public class Employee
{
private String name;
private Date hireDate;
public Employee( )
{
name = "No name";
hireDate = new Date("Jan", 1, 1000); //Just a placeholder.
}
/**
Precondition: Neither theName nor theDate is null.
*/
public Employee(String theName, Date theDate)
{
if (theName == null || theDate == null)
{
System.out.println("Fatal Error creating employee.");
System.exit(0);
}
name = theName;
hireDate = new Date(theDate);
}
public Employee(Employee originalObject)
{
name = originalObject.name;
hireDate = new Date(originalObject.hireDate);
}
}
受薪员工:
public class SalariedEmployee extends Employee
{
private double salary; //annual
public SalariedEmployee( )
{
super( );
salary = 0;
}
/**
Precondition: Neither theName nor theDate are null;
theSalary is nonnegative.
*/
public SalariedEmployee(String theName, Date theDate, double theSalary)
{
super(theName, theDate);
if (theSalary >= 0)
salary = theSalary;
else
{
System.out.println("Fatal Error: Negative salary.");
System.exit(0);
}
}
public SalariedEmployee(SalariedEmployee originalObject )
{
super(originalObject);
salary = originalObject.salary;
}
}
管理员:
//Create a test program that uses scanner so person can input values for the admin class.
public class Administrator extends SalariedEmployee
{
private String title;
private String responsibility;
private String supervisor;
//No argument Constructor
public Administrator( )
{
super( );
title = "No Title";
responsibility = "No Responsibility";
supervisor = "Dilbert";
}
//3 argument constructor
public Administrator(String theTitle, String theResponsibility, String theSupervisor)
{
super( );
if (theTitle == null || theResponsibility == null || theSupervisor == null)
{
System.out.println("Fatal Error creating employee.");
System.exit(0);
}
title = theTitle;
responsibility = theResponsibility;
supervisor = theSupervisor;
}
//6 argument Constructor
public Administrator(String theName, Date theDate, double theSalary, String theTitle, String theResponsibility, String theSupervisor)
{
super(theName,theDate,theSalary);
title = theTitle;
responsibility = theResponsibility;
supervisor = theSupervisor;
}
}
我尝试使用以下方法创建一个新的管理员对象:
Administrator admin = new Administrator();
但是我收到一个致命错误。我究竟做错了什么?
最佳答案
您的Date类以无信息的方式在所有地方输出“致命错误”(直到您发布Date类代码,我们才知道)。
第一次出现致命错误是在setDate
方法内部,因为dateOK
为"Jan", 1, 1000
返回了false。
您的monthOK
方法需要"January"
,因此用于默认构造函数的"Jan"
无效。更改默认构造函数以使用
hireDate = new Date("January", 1, 1000);
关于java - 构造函数继承在新对象上出现致命错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25878210/