This week's book giveaway is in the Agile and Other Processes forum.
We're giving away four copies of Real-World Software Development: A Project-Driven Guide to Fundamentals in Java and have Dr. Raoul-Gabriel Urma & Richard Warburton on-line!
See this thread for details.
Win a copy of Real-World Software Development: A Project-Driven Guide to Fundamentals in Java this week in the Agile and Other Processes forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Liutauras Vilda
  • Knute Snortum
  • Bear Bibeault
master stewards:
  • Devaka Cooray
  • Jeanne Boyarsky
  • Junilu Lacar
garden masters:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • salvin francis
gardeners:
  • Tim Holloway
  • Piet Souris
  • Frits Walraven

Casting ......confusion

 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Why does this code....compiles and runs fine.
class Base {}
class Sub extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s=new Sub();
b =s;
s=(Sub)b;
}}
But, at the same time this code produces Runtime ....ClassCastexception
class Base {}
class Sub extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s=new Sub();
s=(Sub)b;
b =s;
}}
can someone please explain.
Thanks,
Mukti
 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your 1st code b points to a class Sub object. In your 2nd code b does not points to a class Sub object. Down casting is not allowed.
 
Please enjoy this holographic presentation of our apocalyptic dilemma right after this tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!