2013-10-25 133 views
1

我有一個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); 
+2

這應該是'esp.grantStock(m);' –

+4

'instanceof'不'查找方法'。你在某個地方有一個基本的誤解。 – EJP

回答

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

你必須調用EmployeeStockPlan對象的grantStock()方法,否則Java的是要尋找它的主類,它沒有按」沒有那種方法。

esp.grantStock(m); 
+1

由我複製anwser,你更快:)然後 –

+0

@ X-Pippes它不是你的答案的重複。你錯誤地聲稱他需要創建一個他已經實例化的類的實例。 – EJP

+0

就是這樣,非常感謝Jesper! –