TheFunk TheFunk - 2 months ago 5
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

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

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
list using

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


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.