• 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
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

A cast problem!!

 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Run this program, and output "a instanceof B." , "a instanceof A". My question is : if a is instance of A, why it will throw the ClassCastException at runtime?
regards,
Kelvin
 
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you can't upcast run-time types... D extends A so an object of D can be casted to A, but an object of run-time type A can't be casted to D.
In this case the run-time type of a is actually B, you can't cast B to a D as they have no relation in the first place.
Compiler checks reference type not actual object run-time type, that's why code didn't make a compiler error, but at run-time the JVM knows what actual run-time type the object refered by the reference is..
HTH
 
Kelvin Mak
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
o, ic, thx a lot.
reply
    Bookmark Topic Watch Topic
  • New Topic