aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes downcasting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "downcasting" Watch "downcasting" New topic
Author

downcasting

Howard Kung
Greenhorn

Joined: Jul 22, 2002
Posts: 24
Hi all,
I'm doing the mock exam on www.jchq.net. I have a question about the following:
class Base {}
class Sub extends Base {}
class Sub2 extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s=(Sub) b;
}
}
1) Compile and run without error
2) Compile time Exception
3) Runtime Exception
The answer is 3. But why? I thought Sub s=(Sub) b has the the downcasting already. So why exception in runtime?
Thanks in advance


Howard Kung<br />SCJP 1.2<br />SCWCD<br />IBM Certified Specialist: WebSphere 4.0
Anthony Villanueva
Ranch Hand

Joined: Mar 22, 2002
Posts: 1055
Hi, Howard. You have to differentiate an object reference from the object that it refers to, because they can be of different types. Sort of.
Suppose I declare
Base b
b is an object reference that can refer, or point to an object which is of type B or any of its subclasses. So I can do this:
b = new Base();
b = new Sub();
b = new Sub2();
Casting only affects the object references, not the objects being referred to. We can do this
Sub s = new Sub();
Base b = s;
This is considered a widening conversion, and no explicit cast is required.
We can also do this, provided we make an explicit cast
Base b = new Base();
Sub s = (Sub) b;
This is a narrowing conversion. This will compile, but will throw an exception at runtime, because the object being referred to by b is an object of type Base, and the object reference s can only point to objects of type Sub or its subclasses.
If it had been
Base b = new Sub();
Sub s = (Sub) b;
then it will work. The object referred to by b is really of type Sub, so s can "hold" it.
[ August 07, 2002: Message edited by: Anthony Villanueva ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: downcasting