Can anybody explain why the if statement below evaluates false?
public void addShapeToWhiteboard(PolyLine shape)
{
Window.alert("2");
if(shape instanceof PolyLine)
{
Window.alert("3");
this.whiteboard.add((PolyLine)shape);
Window.alert("3.5");
}
this.whiteboard.draw();
Window.alert("4");
}
it takes in a "PolyLine" object, but instanceof returns false because I get an alert of "2" followed by an alert of "4" and have no clue how it's even possible.
instanceof is a binary operator we use to test if an object is of a given type. The result of the operation is either true or false. It's also known as a type comparison operator because it compares the instance with the type. Before casting an unknown object, the instanceof check should always be used.
As the name suggests, instanceof in Java is used to check if the specified object is an instance of a class, subclass, or interface.
instanceof can be used to test if an object is a direct or descended instance of a given class. instanceof can also be used with interfaces even though interfaces can't be instantiated like classes.
The isInstance method is equivalent to instanceof operator. The method is used in case of objects are created at runtime using reflection. General practice says if the type is to be checked at runtime then use the isInstance method otherwise instanceof operator can be used.
Maybe shape is null? instanceof returns false in such a case.
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