Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When does Class Cast Exception occur?

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • 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.
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • 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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic