Java Reference
In-Depth Information
downcasting
15
so that in the worst case scenario, your program has a nice, clean
type exception. You simply do not get the kind of “mystery bugs” that you can
get in C++ when you miscast an object.
16
Thanks to interfaces and a true single object hierarchy, many of the uses
of C++ templates go away. We doubt very much that you will miss them. In
many cases, such as STL algorithms and other functional programming imple-
mentations, you can use interfaces to produce similar results.
Critics of the Java language have a point when they complain that all the
type casting of class references in order to expose desired interfaces tends to
produce code that violates object-oriented principles. The fact that a class or
interface implements all these other named interfaces is hard-coded all over the
place in an application's code. Such critics say this is a bad thing, because it vi-
olates encapsulation and implementation hiding. These critics have a point. If
you find yourself frequently downcasting object references, consider using the
Java 5.0 generics, or try to find another way to code what you want to do.
There may be a better way. In defense of the original Java approach (before
generics), all casts are runtime type safe. An exception is thrown if a class refer-
ence is improperly cast. In C++, if you miscast a pointer, it assumes you meant
it. Java certainly can be awkward, but errors will get caught. Sometimes that is
more important.
3.6
V
IRTUALLY
F
INAL
One difficulty anyone writing about Java faces is whether or not to assume your
readers are familiar with C++. In this chapter, we have tried to help those with
C++ experience without requiring such knowledge. But it is in the inevitable
comparisons between those languages that many subtle Java features are best
discussed. We promised you that we would talk about the relative merits of
virtual
(a C++ concept) and
final
(a Java concept). To do that, we have to
assume some knowledge of C++. So, let's reverse the pattern and talk about the
15. Don't worry if this is all gibberish to you right now. We will revisit these topics in detail
when we come upon them in the course of our sample project.
16. Actually, we're being a bit optimistic here. While Java programs are not subject to many
mystery bugs, the Java Virtual Machines that run Java code are written in traditional languages,
and there have been VMs with bugs. Time and again we see that there is no “silver bullet.” But
in our experience, Java comes close. So very close.