Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

downcasting  RSS feed

Howard Kung
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I'm doing the mock exam on 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
Boost this thread!