• 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 ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How casting is done in this example

 
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
what is the putput and why

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


Regards
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Supriya Nimakuri:
what is the putput and why

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


Regards



At compile-time, a cast to a subclass is allowed.

However, at runtime, you can't cast a reference to a Base object to a reference to a Sub object.

A Base object is not a Sub object.
 
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


your code compiles fine as there is an inheritance relationship between the two i.e., between the type of b and Sub class. No matter who is super class of whom?

At runtime, b actually point to an instance of Base so can't be casted to any Subclass.
It can only be casted to Base or superclass of Base like Object.

So correct answer is...

2) Compile time Exception

which is ClassCastException at runtime.


Naseem
[ June 28, 2006: Message edited by: Naseem Khan ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic