java instanceof not finding method

Posted by Razvan N on Stack Overflow See other posts from Stack Overflow or by Razvan N
Published on 2013-10-25T09:48:49Z Indexed on 2013/10/25 9:54 UTC
Read the original article Hit count: 225

Filed under:
|

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.

The Employee class:

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;


}

}

The Manager class:

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;
}

}

The EmployeeStockPlan class:

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);

© Stack Overflow or respective owner

Related posts about java

Related posts about instanceof