The moose likes Beginning Java and the fly likes Downcasting allowed or not ??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Downcasting allowed or not ???" Watch "Downcasting allowed or not ???" New topic
Author

Downcasting allowed or not ???

Sabyasachi Chowdhury
Greenhorn

Joined: Jul 22, 2004
Posts: 7
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
Darin Niard
Ranch Hand

Joined: Jun 08, 2004
Posts: 118
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

Joined: Jul 22, 2004
Posts: 7
Does that means Downcasting is not allowed in Java? As my original question was !!!
Darin Niard
Ranch Hand

Joined: Jun 08, 2004
Posts: 118
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.
 
wood burning stoves
 
subject: Downcasting allowed or not ???