Advertisement

[java] Casting: narrow->wide->narrow

Started by December 22, 2000 05:01 PM
0 comments, last by Spyder 24 years ago
Example. You have class: Shape
Subclasses that extend shape: Rect, Box, Sphere

You have Rect and want to make it a Box. Is there a faster way of doing this than:
Shape newshape= (Shape) box;
Rect rect=newshape;
I don''t think that will even work... First, the way you have that set up, it won''t even compile. To compile, you need the cast on the narrowing conversion, not the widening one. But after fixing that, it still won''t work...

It will generate a ClassCastException at runtime, because Box and Rect are not compatible classes... To actually convert between the two, you''d need something like a makeBox() method in the Rect class, and a makeRect() method in the Box class. Depending on how you implement those, it could be set to either copy the shape, or have them share a backing so that changes to one affect the other. Either way, though, it can''t be done with casting.

This topic is closed to new replies.

Advertisement