• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

interface and class casting

 
Ranch Hand
Posts: 352
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
No prison can hold Chairface Chippendale. And on a totally different topic ... my stuff:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic