Forums Register Login
down cast only throw exception
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
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.
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
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.

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.
Simple point to remember is

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

Hoe this anwers your question.

This thread has been viewed 1085 times.

All times above are in ranch (not your local) time.
The current ranch time is
Oct 19, 2018 17:49:08.