3.5. O, Templates! Where Art Thou?Programmers familiar with C++ may be wondering how in the world an OOP language without templates can be useful.
Note
Actually, something very much like templates is available in Java 5.0.
[14]
A new feature, which Sun calls
generics
, looks an
Speaking as programmers who worked with C++ before it had templates, we can sympathize. Java's previous lack of true templates does impose some limits on generic programming, but not as much as one might think. Remember that unlike C++, all Java classes inherit from exactly one base class, and that if no base class is specified, they extend the
Object
class. This means that every single Java class either directly or indirectly extends
Object
, and thus all Java classes are instances of
Object
. So if you need, for example, to implement a container, you can guarantee that it can contain any Java class by implementing a container for the
Object
type. Java also has runtime type identification features that are more than a match for anything C++ has, plus it has type-safe
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
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
|
3.6. Virtually Final
One difficulty
In Java, a method or a class may be declared final . A method that is declared final may not be overridden in classes that extend the class containing the final implementation. A class that is declared final may not be extended at all.
Now, the comparisons to C++ require us to talk about a language feature that does not exist at all in Java. In C++, unless a method is declared
virtual
, when a class is used by reference to a base class (for example, when using
Employee
as a
Person
), the base class version of the method is called. If the method is declared virtual, the version of the method called is the version for the type of
Person
referenced (in this case,
Employee
). In Java, all
|