Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java's instanceof odd behavior

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.

like image 888
user1919819 Avatar asked Dec 20 '12 19:12

user1919819


People also ask

What is Instanceof an example of?

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.

Does Instanceof work for subclasses?

As the name suggests, instanceof in Java is used to check if the specified object is an instance of a class, subclass, or interface.

Does Instanceof work for interfaces?

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.

What can I use instead of Instanceof in Java?

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.


1 Answers

Maybe shape is null? instanceof returns false in such a case.

like image 163
pholser Avatar answered Sep 28 '22 01:09

pholser