• 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
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

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 ]
 
Who knew that furniture could be so violent? Put this tiny ad out there to see what happens:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic