Re: If the object is an instance of a class, why was it cast?
bencoe@gmail.com wrote:
It would really be nice if it obviated
the need for such casts inside if branches based on instanceof and
wherever else the object's run-time type is easily shown by static
analysis to be more specific than the reference's type.
I think that this would make things quite a bit more confusing, if I
had to modify my coding style to take into account the fact that I'm
in, for instance, an "instanceof" block. I'd much rather go to the
trouble of habitually casting things -- this really isn't very much
trouble.
In answer to the original question: you have to cast it because, like
Twisted says, the runtime environment is currently only aware that it
has been passed something of the superclass Object -- giving it access
only to the following methods until you cast,
http://java.sun.com/j2se/1.3/docs/api/java/lang/Object.html
This is a slight misstatement of the situation. Java distinguishes between
the variable, whose compile-time type only is known, and the referenced
object, whose full run-time type is known. This has nothing to do with "javac
.... having the IQ of a turnip" but is a deliberate Java feature to support
disciplined coding and the idioms of polymorphism.
The variable of "Object" type can only refer to methods known to the "Object"
type because that is the type of the variable. Turnip-brained or otherwise,
there is no way at compile time to determine that obj should have access to
methods of other types. By declaring the variable "Object", the programmer is
deliberately telling the compiler only to make Object attributes available to
it. To infer otherwise is for the compiler to predict all runtime scenarios -
not feasible.
Casting the expression to a subtype informs the compiler that, if the cast is
permitted, the expression has access to the attributes and methods of that
subtype.
One should not denigrate this valuable and useful aspect of the Java language.
--
Lew