Java Reference
In-Depth Information
do not need it since we are dealing with only one object. This is the middle dia-
gram in Fig. 12.2. Thus, we see that object ob is a one-dimensional structure,
moving upward to superclasses.
To the right in Fig. 12.2, we show the object modified to take into account
the fact that G implements I —we added a second dimension to the object, plac-
ing at the end of the arrow the names of all components of interface I .
Casting about in the object
You already know that you can cast object ob to a superclass like F :
Activity 12-2.1
presents this
material in a
far more
understandable
fashion!
F fl= (F) ob;
Since this is a widening cast, Java performs it automatically when necessary.
Furthermore, using name f1 , you can reference only components defined in F
and its superclasses, even though the object contains other components. But you
can always cast back to the subclass if you know what that subclass is:
G g= (G) f1;
In the same way, interface I can be used as a type name, and you can cast object
ob to I , using the expression (I) ob , as in
I in= (I) ob;
Here, I is the type of variable in , so you see that interface names can be used as
types. Also, this is a widening cast, so we can actually write this statement as:
I in= ob;
and Java will perform the cast automatically.
In our diagrams of objects as drawn to the right in Fig. 12.2, upward casts
(those that follow an arrow) will be performed automatically, while downward
casts (those that follow an arrow backward) have to be given explicitly.
Consider a method that has a parameter of type I :
void meth(I par) { ... };
a0
Object: ...
Object: ...
Object
...
ob a0
F
F: ...
F: ...
I: p(C)
...
G
G: b
G() p(C)
G: b
G() p(C)
b
G() p(C)
Figure 12.2:
Object a0 , a 1-dimensional view, and a 2-dimensional view showing interface it implements
 
Search WWH ::




Custom Search