我是一名涉及Java的网络开发人员(再次),我遇到了麻烦。
基本上,我有一个超类Employee,它有两个扩展它的子类,叫做Management和Programmer。 Employee类包含一个数组employees
,它基本上是一个Employee对象数组。
以下是两个类(Employee和Management)和最终主要方法的重要摘要。我将在底部解释输出。
public class **Employee** {
private static String firstName;
protected static int MAXEMPLOYEES = 5;
protected Employee[] employees = new Employee[MAXEMPLOYEES];
protected int totEmployees = 0;
public Employee(String first) {
setFirstName(first);
}
public void setFirstName(String str){
firstName = str;
}
public String getFirstName(){
return firstName;
}
public boolean addEmployee(String fname) {
boolean added = false;
if (totEmployees < MAXEMPLOYEES) {
Employee empl = new Employee(fname);
employees[totEmployees] = empl;
added = true;
totEmployees++;
}
return added;
}
}
public class **Management** extends **Employee** {
private String title = "Project Manager";
public Management(String fname, String t){
super(fname);
title = t;
}
public boolean addManagement(String fname, String t){
boolean added = false;
if (totEmployees < MAXEMPLOYEES) {
employees[totEmployees] = new Management(fname, t);
added = true;
totEmployees++;
}
return added;
}
}
-------------------------------------
package employee;
public class EmployeeApplication {
public static void main(String[] args) {
Employee[] empl = new Employee[3];
empl[0] = new Employee("Kyle");
empl[1] = new Management("Sheree", "Director");
System.out.println(empl[0].getFirstName());
}
}
现在,我希望系统打印出“Kyle”,但它打印出“Sheree”。任何想法???
答案 0 :(得分:7)
private static String firstName;
您将firstName
设为静态,这意味着所有实例共享相同的名称。您需要删除静态修饰符,以便不同的Employees具有不同的名称。您还需要将私有访问修饰符更改为protected,以便子类继承该字段。
答案 1 :(得分:2)
private String firstName;
删除static
;
Kyle被Sheree覆盖,这就是你获得输出的原因