• 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

casting

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
my question is

interface I1 {}
interface I2 {}
class Base implements I1 {}
class Sub extends Base implements I2 {}
class Orange {
public static void main(String args[]) {
Base base = new Base();
I1 i1 = base; // 1
Sub sub = (Sub)base; // 2
}}

Result is Run-time error at line 2

any one explain this question why runtime error come at 2 properly casting
is done .

why runtime error come?

Base base=null;
then casting it would come any runtime error .
why?
 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You get a runtime error because you are attempting to cast an object to an invalid type. That is, the object referenced by "base" is not of type Sub, so you cannot cast it to Sub.

The reason you get a runtime error and not a compile time error is it is possible for an object of type Base to also be of type Sub. The compiler cannot know whether or not the cast is valid. The validity of the cast can only be determined at runtime. If you attempt to cast an object to a type it does not implement or extend, you will get a ClassCastException.

Robert


Originally posted by venkataraman muthuvel:
my question is

interface I1 {}
interface I2 {}
class Base implements I1 {}
class Sub extends Base implements I2 {}
class Orange {
public static void main(String args[]) {
Base base = new Base();
I1 i1 = base; // 1
Sub sub = (Sub)base; // 2
}}

Result is Run-time error at line 2

any one explain this question why runtime error come at 2 properly casting
is done .

why runtime error come?

Base base=null;
then casting it would come any runtime error .
why?

 
venkataraman muthuvel
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for ur replay
bye
venkat
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic