wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes When does Class Cast Exception occur? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "When does Class Cast Exception occur?" Watch "When does Class Cast Exception occur?" New topic
Author

When does Class Cast Exception occur?

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
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

Joined: Jul 22, 2000
Posts: 9044
    
  10
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 ]


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When does Class Cast Exception occur?
 
Similar Threads
Inner Class - Initialization Sequence
Package Question II
How to implement hashCode()
When NullPointerException, when "null"?
method invocation