Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting

 
nupur dhawan
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
code:
1. interface I1 {}
2. interface I2 {}
3. class Base implements I1 {}
4. class Sub extends Base implements I2 {}
5.
6. class Orange {
7. public static void main(String args[]) {
8. Base base = new Base();
9. I1 i1 = base;
10. Sub sub = (Sub)base;
11. }
12. }
this gives a runtime error on line 10 when compiled.
isnt downcasting permitted with an explicit cast??
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nupur
the thing to remeber here is the is a principle. You can cast one thing to another when the object being cast is a object of the same type it's being cast to.
In your example Base implments I1 so every Base object is a I1 object. Class Sub extends Base and implements I2, so every Sub object is a Base and is a I2.
In your code you create a Base object called base. The assignment on line 9:
I1 i1 = base;
is OK because you are upcasting the Base object to a I1. An upcast, or widening, is accepted here becauase the obejct being cast is a I1,the type being cast to. You can do implicitly because it is a widening cast.
The cast on line 10:
Sub sub = (Sub)base;
will not compile even though it is an explicit cast because the obejct being cast, a Base object, is not a Sub object.
You could do this if you wanted to:
Base b = (Base)i1;
Here it is ok because the i1 variable refers to an I1 object. That I1 object initially came from a Base object so it is a Base object and can be downcast to one.
hope that helps
 
nupur dhawan
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the explanation Dave .
It helped clarify a lot of my queries .
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by nupur dhawan:
isnt downcasting permitted with an explicit cast??

downcasting with an explicit cast is permitted only when the object you are casting from is the type you are casting to.
 
nupur dhawan
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Thomas ,it is clear to me now .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic