我有一個java instanceof的問題。例如,我有一個名爲Employee的類和其他幾個擴展這個類的經理。我還創建了另一個類EmployeeStockPlan,我想測試instanceof是否正在查找我正在使用的對象。但是,當我從新類調用方法時,出現此錯誤:方法grantStock(Manager)
未定義類型Loader
。對不起,我在java中有些新東西,我希望我不問愚蠢的問題。java instanceof未找到方法
Employee類:
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;
}
}
Manager類:
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);
這應該是'esp.grantStock(m);' –
'instanceof'不'查找方法'。你在某個地方有一個基本的誤解。 – EJP