我刚刚了解了超类和子类,并且作业非常简单:有2个类和一个测试类来调用和打印属性。下面是我所有3个类的代码。我的问题是,为什么部门不在我的主要部门打印?其他所有内容都可以正常打印,但我无法打印最后一点。我认为这与超级...有关,请先谢谢!第二门计算机课程,我终于感觉到我可以接受,所以这比我上的第一堂课有所改善!
public class Employee {
private String firstName;
private String lastName;
private int employeeID;
private double salary;
public Employee () {
firstName = null;
lastName = null;
employeeID = 0;
salary = 0.00;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getEmployeeID() {
return employeeID;
}
public double getSalary() {
return salary;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmployeeID(int employeeID) {
this.employeeID = employeeID;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String employeeSummary () {
String employeeSummary = "Employee's name is: " + getFirstName() + " " + getLastName() +
". The employee's ID number is " + getEmployeeID() +
". The employee's salary is " + getSalary();
System.out.println(employeeSummary);
return employeeSummary;
}
}
public class Manager extends Employee {
private String departmentA;
public Manager() {
super();
departmentA = null;
}
public String getDepartmentA() {
return departmentA;
}
public void setDepartmentA(String departmentA) {
this.departmentA = departmentA;
}
public void EmployeeSummary() {
super.employeeSummary();
System.out.println("The employee's department is " + departmentA);
}
}
public class ManagerDerivation {
public static void main(String[] args) {
Manager person = new Manager();
person.setFirstName("Ron");
person.setLastName("Weasley");
person.setEmployeeID(2345);
person.setSalary(65000.00);
person.setDepartmentA("Department of Magical Law Enforcement");
person.employeeSummary();
return;
}
}
方法名称区分大小写。 EmployeeSummary()
不会覆盖employeeSummary()
,因为它使用了不同的名称。
为了避免此类错误,请始终在覆盖的方法上包含@Override
annotation。如果您包含该注释并在方法签名中出错,则编译将失败。
还请注意,两种方法的返回类型不同(@Override
和String
)。重写的方法必须具有兼容的返回类型。
[存在一些拼写错误(employeeSummary与EmployeeSummary),并且返回类型不匹配,在Employee中应该是
void
然后进入Manager
public void employeeSummary () {
String employeeSummary = "Employee's name is: " + getFirstName() + " " +
getLastName() +
". The employee's ID number is " + getEmployeeID() +
". The employee's salary is " + getSalary();
System.out.println(employeeSummary);
}