Search code examples
javainheritanceinstance

Best way to check whether the instance of parent class rather than child class?


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


Solution

  • 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
    }