Let’s say that I have a class A, and that B,C,D are derived from A.
If I want to know what’s the type of an object referenced, I can declare:
// pseudo-code
if(obj instanceof B)
< is B>
else if(obj instanceof C)
< is C>
else
<is D>
This because I am sure that the classes derived from A are only B,C and D.
But what if I want just to check that two references point to the same kind of object?
So something like:
if(obj1 instanceof obj2)
<do something>
But of course the syntax is wrong.How to check this without one thousand if-else?
You mean something like
This should return true just if both
obj1andobj2are of the same specific class.But this won’t work if you are comparing
AwithB extends A. If you want equality that returns true even if one is a subtype of another you will have to write a more powerful comparison function. I think that you can do it by looping withgetSuperClass()to go up the hierarchy tree.I think a simple solution can be also to do
A.getClass().isAssignableFrom(B.getClass()), assuming thatB extends A.