I have a problem with java instanceof. I have a class called Employee and several others that extend this one, for example - Manager. I also created another class,EmployeeStockPlan, where I wanted to test if instanceof is finding which object I am using. But when I am calling a method from the new class, I have this error: The method grantStock(Manager) is undefined for the type Loader. Sorry, I am somehow new to some thing in java, I hope I am not asking dumb questions.
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;
}
}
The main class:
EmployeeStockPlan esp = new EmployeeStockPlan();
Manager m = new Manager (12421, "Manager1", "111-4254-521", 2430, "Marketing1");
grantStock(m);
해결책
EmployeeStockPlan esp = new EmployeeStockPlan();
Manager m = new Manager (12421, "Manager1", "111-4254-521", 2430, "Marketing1");
grantStock(m);
You have to call the grantStock() method on the EmployeeStockPlan object, otherwise Java is going to look for it in the main class, which doesn't have that method.