Testing `instanceof` is redundant and can be replaced with`! = Null`?

In AndroidStudio, which uses intellij, I get the following suggestion in my code. I was wondering why this suggestion is made.

I have several classes Child

that inherit from ParentB

and ParentB

inherit from ParentA

.

I have a condition that should check which of the child classes I have ParentB

. Tell me I have 4 children. ChildA

, ChildB

, ChildC

, And ChildD

. All of these children are inherited from Child

.

So, I have the following:

public void test(Child myChild) {

    anotherTest((ChildA)myChild);
    if (myChild instanceof ChildA) {
        //dosomething
    } else if(myChild instanceof ChildB) {
        //dosomething
    }
}

public void anotherTest(ChildA theChild) {
    //dosomething
}

      


public ParentB extends ParentA {
}

public Child extends ParentB {
}

public ChildA extends Child {
}

      

When I test the condition, I get the following sentence. Condition "myChild instanceof ChildA" is redundant and can be replaced with "!=null"

...

Why am I getting this offer? Is the proposal accurate?


Edit.

I added a method before the condition. After commenting out the method, he removes the sentence. This is because he is already trying to pass it on ChildA

and could not be there. So the ideal just assumes it goes through there and says you can just check for zero after that?

thank

+3


source to share


2 answers


If myChild is not an instance of ChildA (and not null), you will get a ClassCastException when you call anotherTest ().



This way, your if block is only available when myChild is null or a ChildA instance and your validation instance is redundant.

+7


source


Happening:

if(obj instanceof MyClass) {...}

      

and

if (obj == null) {...}

      

returns false in both cases if the object is not null. This is because a null reference is not an instance of anything. It makes sense. But instanceof

it is not redundant. It's the other way around. Checking explicitly for null is redundant if you need to check if a particular object is an instance of some class. For example:

if(obj == null) {...} // This check is redundant
else if (obj instanceof MyClass) {...}

      



Therefore, the clause " Condition" myChild instanceof ChildA "is redundant and can be replaced with"! = Null " " is not entirely accurate.

Apple apple = new Apple();
Orange orange = new Orange();

      

None of these objects are null and they are not compatible ( instanceof

) with each other.

if (apple instanceof Orange) {...} // false
if (orange instanceof Apple) {...} // false
if (apple != null) {...} // true: does this mean an apple 'is-an' orange?
if (orange != null) {...} // true: does this mean an orange 'is-an' apple?

      

Conclusion . Checking object references with is instanceof

not redundant because it includes null checking.

0


source







All Articles