1

我对 java instanceof 有疑问。我有一个名为 Employee 的类和其他几个扩展这个类的类,例如 - Manager。我还创建了另一个类 EmployeeStockPlan,我想在其中测试 instanceof 是否正在查找我正在使用的对象。但是当我从新类调用一个方法时,我有这个错误: The method grantStock(Manager)is undefined for the type Loader。对不起,我对java中的某些东西有点陌生,我希望我不是在问愚蠢的问题。

员工类:

package com.example.domain;

public class Employee {

private int empId;
private String name;
private String ssn;
private double salary;

public Employee(int empId, String name, String ssn, double salary) { // constructor
                                                                        // method;
    this.empId = empId;
    this.name = name;
    this.ssn = ssn;
    this.salary = salary;
}

public void setName(String newName) {
    if (newName != null) {
        this.name = newName;
    }
}

public void raiseSalary(double increase) {
    this.salary += increase;
}

public String getName() {
    return name;
}

public double getSalary() {
    return salary;
}

public String getDetails() { 

    return "Employee id: " + empId + "\n" + "Employee name: " + name;


}

}

经理类:

package com.example.domain;

public class Manager extends Employee {

    private String deptName;

        public Manager(int empId, String name, String ssn, double salary, String dept) {
        super(empId, name, ssn, salary);

    this.deptName = dept;
}

public String getDeptName() {
    return deptName;
}

public String getDetails() {
    return super.getDetails() + "\n" + 
            "Department: " + deptName;
}

}

EmployeeStockPlan 类:

package com.example.domain;

public class EmployeeStockPlan {

         public void grantStock(Employee e) {

                // nothing calculated, just simulating;
        System.out.println("This is an employee!");

    if (e instanceof Manager) {
        // process Manager stock grant
        System.out.println("This is a manager!");
    } else {
        // error - instance of Engineer?
        System.out.println("Not an engineer!");
    }
    return;
}

}

主要类:

 EmployeeStockPlan esp = new EmployeeStockPlan();
  Manager m = new Manager (12421, "Manager1", "111-4254-521", 2430, "Marketing1");
  grantStock(m); 
4

1 回答 1

6
EmployeeStockPlan esp = new EmployeeStockPlan();
Manager m = new Manager (12421, "Manager1", "111-4254-521", 2430, "Marketing1");
grantStock(m);

您必须在对象上调用该grantStock()方法EmployeeStockPlan,否则 Java 将在没有该方法的主类中查找它。

esp.grantStock(m);
于 2013-10-25T09:52:48.603 回答