File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "casting" Watch "casting" New topic


nupur dhawan
Ranch Hand

Joined: Jun 26, 2002
Posts: 71
1. interface I1 {}
2. interface I2 {}
3. class Base implements I1 {}
4. class Sub extends Base implements I2 {}
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
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

Joined: Jun 26, 2002
Posts: 71
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
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.

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
nupur dhawan
Ranch Hand

Joined: Jun 26, 2002
Posts: 71
Thank you Thomas ,it is clear to me now .
I agree. Here's the link:
subject: casting
It's not a secret anymore!