Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Deeper explanation of "instanceof" needed.

Status
Not open for further replies.

musik

Programmer
Nov 20, 2001
33
0
0
US
I'm confused. Since (a instanceof b) won't even compile unless you have compatible types on both sides, what use is it? I mean, I already have to know that a is declared as type b or as a child of type b, so... what's the magic of having an operator tell me? And if it's only telling me "yeah, it's been instantiated" or "no, it hasn't been", wouldn't (a != null) yield exactly the same information?

Originally, I thought instanceof would tell you IF a was a member of b or one of b's children, i.e. I expected:

Date a = new Date();
boolean b = (a instaceof String);

to result in b == false. But, this won't compile. (One would have to use aClassInstance.isAssignableFrom() to get that result.)

What am I missing? I know that there must be some good reason for the existence of instanceof! :)

TIA
-DG
 
Why do I figure these things out only after I've posted?

The usefulness, apparently, is if a is declared as some parent type and you're unsure of which child it was actually instantiated to. Changing my example to:

Object a = new Date();
boolean b = (a instanceof String);
boolean c = (a instanceof Date);

works just fine, yielding b==false and c==true. So, it's a way to check which class got instantiated in a particular use of polymorphism.

(Right? :)

(And is there a way to delete a post? I would have just deleted my first post and gotten rid of the thread, but it didn't appear to be possible.)

-DG
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top