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??
Nupur. <br />SCJP2.
Dave Vick
Ranch Hand
Joined: May 10, 2001
Posts: 3244
posted
0
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
Dave
nupur dhawan
Ranch Hand
Joined: Jun 26, 2002
Posts: 71
posted
0
Thank you for the explanation Dave . It helped clarify a lot of my queries .
Thomas Paul
mister krabs
Ranch Hand
Joined: May 05, 2000
Posts: 13974
posted
0
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.