• 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

When does Class Cast Exception occur?

 
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When does a ClassCastException occur during Runtime?
Why doesn’t an explicit cast from Object to a specific class
Cause a class cast exception?
When Object class would be a common Base class like Base{}
Is in Star1a then a ClassCastException would occur.
WHY does Star1b cause NO ClassCastException`?

 No ClassCastException when cast from Object to subclass of Object.

 Excplicit cast from Base class „Base“ to subclass „Star1“ causes
ClassCastException in line 3 as obj is no subclass
WHY here NO ClassCastException?

 No ClassCastException because of mixed type of s which is a
Star1 instance. If it is an instance of the casted class (Star1) or
A subclass of that class no ClassCastException occurs.
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Thomas Markl:
When does a ClassCastException occur during Runtime?


obj is a Star1 so you are casting a Star1 to a Star1



obj is a Base
obj is an Object
obj is not a Star1.
You are trying to cast a Star1a to a Star1. So you get a ClassCastException.

 Excplicit cast from Base class „Base“ to subclass „Star1“ causes
ClassCastException in line 3 as obj is no subclass
WHY here NO ClassCastException?

 No ClassCastException because of mixed type of s which is a
Star1 instance. If it is an instance of the casted class (Star1) or
A subclass of that class no ClassCastException occurs.

obj is a Star1 regardless of whether it is assigned to a Star1 reference or to an Object reference.

Remember that the reference is a reference and the object is the object. They are two separate things.

[ November 03, 2002: Message edited by: Marilyn de Queiroz ]

reply
    Bookmark Topic Watch Topic
  • New Topic