aspose file tools*
The moose likes Beginning Java and the fly likes down cast only  throw exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "down cast only  throw exception" Watch "down cast only  throw exception" New topic
Author

down cast only throw exception

jacob deiter
Ranch Hand

Joined: Apr 02, 2008
Posts: 576
what problem with this code?

I have class


but I got class cast exception,

it is a down cast only then why it throw exception
Miklos Szeles
Ranch Hand

Joined: Oct 21, 2008
Posts: 142
Hi Jacob,

You try to cast an Object instance to an abc instance which is not possible.
Maybe you wanted to write


Anyway it is advised to use uppercase starting letters for class names.
jacob deiter
Ranch Hand

Joined: Apr 02, 2008
Posts: 576
Polymorphism support down casting,

My code is as follow



But I got casting exception why, is it valid casting or not ?

Please explain the reaon for this also
Miklos Szeles
Ranch Hand

Joined: Oct 21, 2008
Posts: 142
No, you misunderstood something. I advice you to reread the subject.
Just think about it logically:
Class B extends A. It means that B has everything which A has plus it can have some other methods and fields. So whenever you need an A instance you can use a B instance since it contains everything what is needed for the A instance, but you can't use an A instance as a B instance.
An A type reference can hold an A instance and a B instance. If the reference contains a B instance then you can cast your reference to B. In your example the reference contains an A instance(not a B) so you can't cast it to B.


Jarred Olson
Ranch Hand

Joined: Jul 31, 2009
Posts: 37
You can use the instanceof operator to to see if the object you're trying to cast is castable (is that a word) to the type you want. It will prevent you from getting the ClassCastException.
Siva Masilamani
Ranch Hand

Joined: Sep 19, 2008
Posts: 385
Simple point to remember is

Super class reference variable can point to Sub class instance not vice versa.

Hoe this anwers your question.


SCJP 6,SCWCD 5,SCBCD 5

Failure is not an option.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: down cast only throw exception