0

我是一名涉足 Java 的 Web 开发人员(再次),但我遇到了一些问题。

基本上,我有一个超类 Employee,它有两个扩展它的子类,称为 Management 和 Programmer。Employee 类包含一个数组,该数组employees基本上是一个 Employee 对象数组。

这是两个类(Employee 和 Management)的重要片段和最终的 main 方法。我将在底部解释输出。

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”。有任何想法吗???

4

2 回答 2

7
private static String firstName;

您设置了firstName静态,这意味着所有实例共享相同的名称。您需要删除 static 修饰符才能使不同的员工具有不同的名称。您还需要将私有访问修饰符更改为受保护,以便子类继承该字段。

于 2013-04-09T23:11:41.887 回答
2
private String firstName;

删除static

Kyle 被 Sheree 覆盖,这就是为什么你得到那个输出

于 2013-04-09T23:13:12.730 回答