my dog learned polymorphism
The moose likes Beginning Java and the fly likes ClassCastException Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "ClassCastException Exception" Watch "ClassCastException Exception" New topic
Author

ClassCastException Exception

Smita Chopra
Ranch Hand

Joined: Jun 27, 2005
Posts: 45
The following program gives a ClassCastException at runtime


Can you please tell me why doesn't it give an error at compile time when its very clear that assigning Object to String is going to fail.
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

It may be clear to you, but the compiler doesn't have any way of knowing for certain that such a cast won't work. The example posted is trivial; quite often, a particular implementation is unknown at compile-time, so the compiler trusts you know what you're doing when you cast a reference.
Anil Chandran
Greenhorn

Joined: Apr 11, 2005
Posts: 15
Only at runtime it can be made sure that the object cant be casted to a string .

Object is a super class of String . So casting an object to string cant cause a compile time error.


I started out with nothing..I still have most of it ...
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: ClassCastException Exception
 
Similar Threads
Question #3 from Doug's book
Ambiguity in S&B book
"Casting" from a Superclass to a subclass
When does Class Cast Exception occur?
interfaces