This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

downcasting

 
Howard Kung
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic