• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
  • Mikalai Zaikin


Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
    Bookmark Topic Watch Topic
  • New Topic