This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes package importance in instanceof operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "package importance in instanceof operator" Watch "package importance in instanceof operator" New topic

package importance in instanceof operator

Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 528

Does the package that a class is in influence in the instanceof check?


Live life to an interface, not an implementation!
Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 528

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

Joined: Jan 30, 2000
Posts: 18671
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.

"I'm not back." - Bill Harding, Twister
Dave Wood
Ranch Hand

Joined: Aug 02, 2004
Posts: 161
[ 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 ]

Co-Author of <a href="" target="_blank" rel="nofollow">Java Swing</a><br />Co-Creator of <a href="" target="_blank" rel="nofollow">SCJP 5.0</a> and <a href="" target="_blank" rel="nofollow">SCJA</a> exams
Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 528

Thank you both, you have really cleared this up for me. I love this site (and of corse the people which make it be)
I agree. Here's the link:
subject: package importance in instanceof operator
jQuery in Action, 3rd edition