• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

ClassCast Exception question

 
Ranch Hand
Posts: 192
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
The following code compiles and runs. Output is false, true.


but i thought at runtime, this code should throw ClassCastException, since Error and RuntimeException are being referred as type Object. Variables "error" and "runtimeException" are of type object and do not know about subclass "Error" and "RuntimeException"

i am missing something here ? Please help

thanks
 
Sheriff
Posts: 11343
Mac Safari Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The instanceof operator uses the true runtime type of the object, and returns a boolean based on whether the object's reference could be cast to the indicated type without throwing a ClassCastException.

At compile time, the types are checked only for "plausibility." If the relationship is clearly not possible, then a compile-time error results (not a ClassCastException).

In this example, it's plausible a reference of type Object might point to an instance of Exception, so this code compiles. But because the runtime type of error (Error) cannot be cast to Exception (the cast would throw a ClassCastException if attempted), instanceof returns false in that case.
[ January 08, 2007: Message edited by: marc weber ]
 
John Lincoln
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Marc,

Thanks for the response. I missed the minor detail ( if attempted to cast).

thanks again
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic