Reputation: 730
If I have a class A and a child class B extended from A, and I have an instance bbb of B from somewhere, what would be the best to check the instance bbb is not actually of A.
What I can think are the following two. Which is better or anything better than both of them?
1) if(!((bbb instanceof A) && (bbb instance of B)))
2) if(bbb.getClass().getName()!=A.class.getName()){
Thanks
Upvotes: 0
Views: 3025
Reputation: 193
Let's change A for Animal and B for Bird
I you already have an instance of Bird it can't possibly be a "raw" Animal. As Bird is a more specific type of Animal, JAVA won't let you directly assign a "raw" Animal into a Bird variable. If you meant the other way round (you have an Animal and you want to tell if it is actually a Bird) you can do it using
if ( bbb instanceof Bird) ...
In short, if your question is right, you can be sure you have a Bird without the need of checking anything.
Upvotes: 0
Reputation: 48837
bbb
actually is an instance of A
since B
extends A
, so your first solution won't work.
Comparing the classes directly should suit your needs:
if (!A.class.equals(bbb.getClass()))
You could also think differently:
A bbb = ...;
if (bbb instanceof B) {
// bbb has been instantiated via B or one of B subclasses
} else {
// bbb has been instantiated via A or one of A subclasses except B
}
Upvotes: 4