File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes instanceof doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "instanceof doubt" Watch "instanceof doubt" New topic
Author

instanceof doubt

adam Lui
Ranch Hand

Joined: Sep 03, 2007
Posts: 186
whilst


compiles and prints true fine...
look at this one



compile fails!??
i dont understand the logic, can anyone elaborate?
Joshua Mark
Greenhorn

Joined: Sep 23, 2007
Posts: 15
Correct me if I'm wrong here, but your Dog[] is an Array of Dog objects. But non-the-less it's an Array. Calling Dog[] instance of Dog is basically saying Array instanceof Dog, which obviously is false. Hope that helps.
adam Lui
Ranch Hand

Joined: Sep 03, 2007
Posts: 186
i think you are correct,
it is ashame that even an array of Dog as type of dogs cant make it in the instanceof test.

why java creators ever decide it like that?
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11499
    
  16

if i said "is an egg carton an egg", what would you say? odd are you say "Nope, and egg carton is NOT an egg".

An egg carton HOLDS eggs. it's the same with an array of Dogs vs a Dog object.

Further, think of how the instaceof operator is often used...



you can't call the bark() or meow() method on the ARRAY, you have to call it on the object IN the array.
[ November 07, 2007: Message edited by: Fred Rosenberger ]

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
adam Lui
Ranch Hand

Joined: Sep 03, 2007
Posts: 186
Originally posted by Fred Rosenberger:
if i said "is an egg carton an egg", what would you say? odd are you say "Nope, and egg carton is NOT an egg".

An egg carton HOLDS eggs. it's the same with an array of Dogs vs a Dog object.

Further, think of how the instaceof operator is often used...



you can't call the bark() or meow() method on the ARRAY, you have to call it on the object IN the array.

[ November 07, 2007: Message edited by: Fred Rosenberger ]


nice example of logic here Fred, thanks for that!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: instanceof doubt