• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Casting (or conversion) between interface and class

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello guys.
I have questions about cast or conversion between interface and class.
Class A implements Immm
Class B implements Immm
A a;
B b;
Immm iii;
a = new A(); //....line 1
iii = a; //....line 2
b = (B)iii; //....line 3
Compilation is ok and got runtime error with ClassCastException.
My question is what does it mean in line 2 ?
(Assigning class object to interface) :roll:
And also why line 3 compiles successfully ?
(Assigning iinterface to class object) :roll:
Any comments will be appreciated. Thanks.
 
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The most important thing to remember is the is a rule. For example your classes A and B both implement the interface Immm. So you can say that an A object is a Immm object, and the same with any B objects you create.
Line 2 should be ok because the variable a refers to an object that is a Immm object. It is a widening conversion (your going from more specific to less specific) so no cast is needed.
Line 3 will compile because you are doing an explicit cast and the compiler will assume you know what your doing. However, when you get to the runtime it throws an exception because the object refered to by the variable iii is not a B object. It is an A object and a Immm object. But not a B object.
hope that helps
[ May 15, 2002: Message edited by: Dave Vick ]
 
Duksun Choi
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Dave.
It's excellent explanation. Wonderful !!!.
Thanks you so much.
Duksun
 
I was her plaything! And so was this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic