Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Downcasting allowed or not ???

 
Sabyasachi Chowdhury
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • 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
 
Darin Niard
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic