Originally posted by Tony Smith: When would this be necessary? And when would this be a bad idea? Thanks.
You should do this if: 1) you are 100% sure the object is a Child, or a subclass of Child (p instanceof Child returns true). Your object inheritance tree might ensure that. 2) you need the extra methods / fields that Child provides and Parent does not.
If 1) does not hold you may get a ClassCastException if the is not a Child. If 2) does not hold then there is no reason to cast.
Following on from Rob's post, this kind of thing would work:
The compiler assures us the parameter is a Parent or some extension of it, but it can't guarantee that the parameter is a Child. If we left out the instanceof test and somebody passed in a Parent, the (Child)x cast would throw an exception.
This kind of test and cast is often a sign of a design that we should improve, but sometimes it's hard to avoid.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Note that your code, as written, is not valid. We know that the run-time type of p is Parent, not Child (because we can see that you instantiated it that way). Casting is appropriate where the run-time type is actually a child, and it is not, here.
Also, note that you are creating a new Child object and assigning it to c, only to be overwritten in the next line. Are you sure you understand the difference between defining a variable, and initializing it?