TheFunk TheFunk - 3 months ago 7
Java Question

Can Java's instanceof differentiate functionally identical classes?

So let's say I have two nearly identical classes, however they represent objects with key differences. At the moment, those differences aren't really implemented.

So for instance, one class, we'll call it

MorningShiftWorker
, has the exact same methods and same constructor as another, which we'll call
EveningShiftWorker
. Objects of both of these are stored in a list of their supertype
ShiftWorker
.

Logically, it makes sense to separate these two groups, but rather than add additional variables to the mix, I figured I'd just do a check on objects in the
ShiftWorker
list using
instanceof
.

My question is: Is
instanceof
smart enough to differentiate apples from oranges? These two classes are at the moment identical in all but name. Is that enough for
instanceof
to tell them apart, or is there another way I should go about this?

Answer

Yes, instanceof essentially checks to see if the object can be properly cast to the given class. Suppose we have these classes:

public class Fruit {}
public class Orange extends Fruit {}
public class Apple extends Fruit {}

Then in some method we try:

Fruit f = new Apple();
boolean isOrange = f instanceof Orange; //False

This also works for empty/non-functional interfaces.