In AndroidStudio, which uses intellij, i am getting the following suggestion in my code. I was wondering why this suggestion is being made.
I have multiple Child
classes that inherit from ParentB
and ParentB
inherits from ParentA
.
I have a condition that needs to test which child class i have of ParentB
. Let's say that i have 4 children. ChildA
, ChildB
, ChildC
and ChildD
. All these children inherit 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 am testing the condition i get the following suggestion. Condition "myChild instanceof ChildA" is redundant and can be replaced with "!=null"
.
Why am i getting that suggestion? Is the suggestion accurate?
Edit.
I added the method before the condition. After commenting out the method it takes away the suggestion. Is it because it already tries to cast it to ChildA
and would have failed there. So, the ide just assumes it passes there and says you can just check for null after that?
Thanks
If myChild is not an instance of ChildA (and not null) you will get a ClassCastException when calling anotherTest().
So your if block is only reachable when myChild is null or an instance of ChildA and your instanceof check is redundant.
The case:
if(obj instanceof MyClass) {...}
and
if (obj == null) {...}
return false in both cases if the object is not null. This is because a null reference is not an instance of anything. That makes sense. But instanceof
is not redundant at all. It is the other way around. Checking explicitly for null is redundant if you need to check if particular object is an instance of some class. For example:
if(obj == null) {...} // This check is redundant
else if (obj instanceof MyClass) {...}
Therefore, the suggestion "Condition "myChild instanceof ChildA" is redundant and can be replaced with "!=null"" is not accurate at all.
Apple apple = new Apple();
Orange orange = new Orange();
Neither of these objects are null, nor they are 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 using instanceof
is not redundant because it includes the check for null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With