"Hello, Amigo! You've already met the instanceof operator. Today I'm going to tell you how and where it can be used. instanceof is a very simple and efficient operator."
"That sounds like an ad!"
"It really is very simple. It's used like this: «object» instanceof «class»."
It checks whether an object is an instance of a particular class. It's easier than explaining it. Look at this example:
Code | Description |
---|---|
|
isInt will be true. The object referenced by the variable o is an instance of the Integer class. |
|
isInt will be false. The object referenced by the variable o is not an instance of the Integer class. It is a String object. |
|
isFIS will be true. The object referenced by the variable o is an instance of the FileInputStream class. |
"Yes, that is very simple."
"This operator also accounts for inheritance. Check it out."
Code | Description |
---|---|
|
Here we have three class declarations: Animal, Cat, and Tiger. Cat inherits Animal. And Tiger inherits Cat. |
|
isCat will be true. isTiger will be true. isAnimal will be true. |
|
isCat will be false. isTiger will be false. isAnimal will be true. |
And even interfaces:
Code | Description |
---|---|
|
Create two classes: Cat, TomCat and the Moveable interface |
|
isCat will be true. isMoveable will be true. isTom will be true. |
|
isCat will be true. isMoveable will be false. isTom will be false. |
The instanceof operator looks like this: a instanceof B.
In other words, the instanceof operator will return true if:
1) variable a stores a reference to an object of type B
2) variable a stores a reference to an object whose class inherits B
3) variable a stores a reference to an object that implements interface B
Otherwise, the instanceof operator will return false.
"Got it. So why is this necessary, Uncle Rishi?"
"Ellie's going to tell you about that today. This is a really nice operator. You'll be convinced of that today."
GO TO FULL VERSION