• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

package importance in instanceof operator

 
Marcelo Ortega
Ranch Hand
Posts: 528
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does the package that a class is in influence in the instanceof check?
i.e:
 
Marcelo Ortega
Ranch Hand
Posts: 528
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry i accidently clicked on add topic.

i just don�t understand why Collection and Map instances are allowed to be compared but not String and Map?

The instanceof operator is supposed to cause a compile time error if you compare two objects from a different class heirechy??
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The difference is that Collection is an interface, but String is a concrete class. When the compiler sees (b instanceof Collection), it knows that the declared type of b is TreeMap, which does not implement Collection. But (as far as the compiler knows) b may actually be an instance of some subclass of TreeMap which does implement Collection. I don't want to imagine what sort of poorly-conceived design such a class would have, but it's theoretically possible. A subclass of TreeMap could implement any interface as far as the compiler is concerned (though some may be impossible due to method naming collisions, but the compiler isn't going to analyze that particular point here).

On the other hand when the compiler sees (b instanceof String), it knows b is a TreeMap, and that no subclass of TreeMap could ever possibly be a String. They are unrelated types. (Plus String is final.) So the compiler flags this line as an error.
 
Dave Wood
bronco
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[ whoops...Jim and I responded at the same time...and I had mis-read the question anyway, so I'm deleting my response :-) ]
[ July 28, 2005: Message edited by: Dave Wood ]
 
Marcelo Ortega
Ranch Hand
Posts: 528
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you both, you have really cleared this up for me. I love this site (and of corse the people which make it be)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic