This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread 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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "interface and class casting" Watch "interface and class casting" New topic
Author

interface and class casting

Harshana Dias
Ranch Hand

Joined: Jun 11, 2007
Posts: 327
Hey,

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

and i have class C which implements A.

so,

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
Greenhorn

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.


SCJP 6, SCWCD 5
 
 
subject: interface and class casting
 
Similar Threads
type casting
Casting
sub class !
downcasting...
ExamLab Question