Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

interface and class casting

 
Harshana Dias
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic