if:
interface I{}
class A implements I{}
class B extends A{}
class C extends B{}
A a = new A();
B b = new B();
Why a = (B)(I)b; is correct
but b = (B)(I)a; is false?
I find casting to be very confusing, what is the best way to understand if I can down cast or up cast an object?
Your class hierarchy looks like this:
Object x
can be casted to class Y
, if runtime type of x
is subclass of Y
. Or, in other words, if there is a path from runtime type of x
to Y
. By "runtime type" i mean the type of object (the one used when constructing object) as opposed to type of variable (the one from variable declaration).
This is valid:
b = new B();
(B)(I)b;
Object stored in b
has type B
. It's casted to I
and then back to B
. B
is a subclass of both of them. Cast to I
doesn't actually do anything and is meant only to confuse you.
However, neither of those is valid:
a = new A();
(B)(I)a;
(B)a;
They will both fail with exception: java.lang.ClassCastException: A cannot be cast to B
. a
has type A
which is not a subclass of B
. There is a relation between A
and B
, but it's in the opposite direction - B
is a subclass of A
.
For more detailed explanation see here: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
The only thing of relevance to answering the question in your coding sample is the following:
class B extends A{}
This means that B is a subclass of A. Subclasses can be cast to super class types, but super class cannot be cast to subclass types.
Therefore, A cannot be cast to type B.
Why? Think about the logic this way:
is a type of Programming_language
, but Programming_language
is not a type of
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With