Originally posted by Brian Joseph:
If you have:
class A {}
class B extends A {}
B b = (B)new A();
You always get a ClassCastException. It isn't like you are allowed to call methods from class A or anything, right?
You're right, this would'nt be of any value. However, think about building your methods based on abstract classes or interfaces. You might have an abstract class (or interface) Shape and have the appropriate methods like area, center, rotate...
Now, let's say that in some method that deals with Shape as a parameter you want to do behavior that only exists on one of the subclasses. You have to downcast to the appropriate type, or you can't invoke the method. So, the Shape is not (only) a Shape, it is some subclass like Octagon. Assuming that Octagon has some methods that are not generally applicable to Shapes, you have to downcast: Octagon myOct = (Octagon) theShape;
Of course, you might
test it first to avoid the ClassCastException: if (theShape instanceOf Octagon).