java instanceof没有找到方法

时间:2013-10-25 09:48:49

标签: java instanceof

我有java instanceof的问题。我有一个名为Employee的类和其他几个扩展此类的类,例如 - Manager。我还创建了另一个类EmployeeStockPlan,我想测试instanceof是否正在查找我正在使用的对象。但是当我从新类调用方法时,我有这样的错误:方法grantStock(Manager)未定义类型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); 

1 个答案:

答案 0 :(得分:6)

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

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

esp.grantStock(m);