• 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

Downcasting allowed or not ???

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

I just wanted to verify whether downcastinbg is at all allowed in Java or not? Because If I have anything like this.....


This is not allowed right ?
But when I do
B b = (B)a;
This is allowed.People say its downcasting but I think it is no way downcasting it is rather typecasting.

Please let me know whether actually Java does support downcasting or not?

Regards
Sabyasachi Chowdhury
 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A a = new B(); // allowed
B b = new A(); // not allowed

The first works because it is only a reference to a B object as a type A.
The second doesn't work because A is not a subclass of B, and wouldn't fit the description of a B object.

(edit: Basically, you can't call a fruit an apple unless it is an apple, but you can always call an apple a fruit.)


B b = (B)a;

This works because the object referenced by 'a' is actually an object of type B, but is referenced as type A, hence the cast.

(edit: I'm assuming this is consistent with your example code. If you meant that 'a' was actually pointing to an A object, then no, that wouldn't work for the same reason your second line didn't. The only difference is, you would get a ClassCastException at runtime, instead of a compiler error.)
[ July 22, 2004: Message edited by: Darin Niard ]
 
Sabyasachi Chowdhury
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Does that means Downcasting is not allowed in Java? As my original question was !!!
 
Darin Niard
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why, is this a homework question? I told you how it works. Whether or not that fits your definition of 'downcasting' is for you to decide.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic