Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof doubt

 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
whilst


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



compile fails!??
i dont understand the logic, can anyone elaborate?
 
Joshua Mark
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12147
31
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic