This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes interface and class casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "interface and class casting" Watch "interface and class casting" New topic

interface and class casting

Harshana Dias
Ranch Hand

Joined: Jun 11, 2007
Posts: 327

I have interface A and interface B which is the sub interface of A.

and i have class C which implements A.


class C implements A{}

C c =new C();

B bb=(B)c; // for this how the compile and runtime rules apply

Is it like compile time fine because any class (except final)can be cast to interface...
And in Runtime the object type is C (not B right?) and reference type is B so i wont find any relationship between them know? (if those are object classes the rule to be run successfully is the object type should be subtype or sametype right? is there any clear rule like that in interface and class casting too

Thank You.
Raphael Huerta

Joined: Jun 10, 2009
Posts: 2
Hi, when you attemp to compile this code the compiler will not complain, but a run time a ClassCastException will be thrown. This is because interface B is not in the inheritance tree of Class C, it don't have any knowlegde about inteface B.
If class C implements B instead A and then you try cast it to A (A a = (A)c), this will be fine because interface A is in the inheritance tree of Class C since interface B extends A.

I agree. Here's the link:
subject: interface and class casting