Reputation: 1189
Consider the following classes in Java:
interface I{
}
class A implements I{
}
class B extends A {
}
class C extends B{
}
And the following declarations:
A a = new A();
B b = new B();
Once you have a = (B)(I) b;
the code will compile and run. And don't understand why at all I need to cast into Interface and class B. It would work, in my opinion, when a = b;
fine. Can some one explain me the logic of the above explicit casting what make the code run fine.
But once you have I i = (C) a;
it will fail at run-time because 'a' does not point to an object of class C. Why does 'a' needs to point to an object of class C? Besides that I don't get the logic of casting into C class. Anyway you will have reference of I interface. Best regards
Upvotes: 1
Views: 345
Reputation: 30107
Casting of reference types in Java is just a programmer's self-check notation. Variables of that types hold only references (pointers) to objects. During casting neither reference itself, nor referenced object changes. Actually such casting does nothing.
The need for self check is only required while assigning broad-typed variable to narrow-typed. For example from superclass to subclass. Because an error possible only here. While assigning from equal-typed variabled or from narrower-typed, no check required, since it is always possible.
Upvotes: 0
Reputation: 691755
Casting an object to a given class or interface is only possible if the casted object indeed extends this class or implements this interface. If it does not (i.e. if the object is not an instance of the the class or interface), you'll get a ClassCastException. Notev that casting an object to a class doesn't change the type of the object. It only allows referencing it as another type, that it also is, extends or implements.
Let's see your examples:
a = (B)(I) b;
This first casts the object b
, which is of type B
. to the interface I
. This is OK since B extends A, and A implements I, which means that B also implements I.
Then it casts the same object a second time to the class B
. b
is an instance of B
, so this works.
I i = (C) a;
This casts the object a
, which is of type A
, to the class C
. A doesn't extend C, so this is impossible.
Upvotes: 2