instanceOf in a Controller class ok? (Cannot edit any other class)

83 views Asked by At

The project has 4 classes. A Person, an Employee that extends Person and an Academic that extends Employee. I also have a Store, which is a user-made alternative to an Array. One of the functions of Store is ‘elementAt()’, which returns to us an object in Store.

The problem I have is that elementAt() always returns as type Person. This is a huge problem because, in my Controller class, before I let the user perform an action only applicable to an Academic I NEED to check whether the user has actually chosen an employee or not.

public Person elementAt(int index)
{
// Returns element at position index
return list[index];
}

There is one big problem; according to the project specification I cannot alter the Person, Employee, Academic or Store class any further. Meaning, I have to determine the type of the Store index somewhere, somehow within my controller class.

I wanted to run this by people with more experience so thank you for having a look.

2

There are 2 answers

0
Uwe Allner On BEST ANSWER

Instanceof seems to me the only option you have; and I don't think that its evil to use it in this case. But you are right, it is not the nicest thing in thinking in objects ;o)

At least you might encapsulate that like

public boolean isAcademic(Person p) {
    return p instanceof Academic;
}

to concentrate the "code smell" in one position, and make it easier to later refactor it.

2
Thiago Duarte On

I don't know if i got it right, but if you just want to check the returned object type, do this:

Person person = store.elementAt(0);
if (person instanceof Academic) {
   //do stuff
}