Java Reference
In-Depth Information
class AClass {
void aMethod () { ... }
}
class BClass extends AClass {
void bMethod () {...}
}
In the following code, miscMethod() is declared to receive an AClass object
as a parameter. When used, the actual object passed in might in fact be an instance
of BClass ,which is perfectly legal since BClass is a subclasses of AClass .
public void miscMethod (AClass obj) {
obj.aMethod ();
if (obj instanceof BClass) ((BClass)obj).bMethod ();
}
We see that we can invoke aMethod() on the object received in the parameter list
whether that object is an AClass or a BClass since both types have this method.
However, to invoke the bMethod() ,weneed first to check the object type. We
use the instanceof operator to find out if the object really is a BClass and
then cast to BClass if appropriate. Without the cast the compiler complains that
it cannot find bMethod() in the AClass definition.
4.6.2 Casting rules
The casting rules can be confusing, but in most cases common sense applies.
There are compile-time rules and runtime rules. The compile-time rules are there
to catch attempted casts in cases that are simply not possible. For instance, suppose
we have classes A and B that are completely unrelated - i.e. neither inherits from
the other and neither implements the same interface as the other, if any. It is
nonsensical to attempt to cast a B object to an A object, and the compiler does not
permit it even with an explicit cast. Instead, the compiler issues an “inconvertible
types” error message.
Casts that are permitted at compile-time include casting any object to its own
class or to one of its sub- or superclass types or interfaces. Almost anything can
be cast to almost any interface, and an interface can be cast to almost any class
type. There are some obscure cases (see the Java Language Specification for the
details), but these common sense rules cover most situations.
The compile-time rules cannot catch every invalid cast attempt. If the compile-
time rules permit a cast, then additional, more stringent rules apply at runtime.
These runtime rules basically require that the object being cast is compatible
with the new type it is being cast to. Else, a ClassCastException is thrown
at runtime.
 
Search WWH ::




Custom Search