Java Reference
In-Depth Information
list class that is type-safe. You look at the standard class in the
java.util
package that implements a
linked list using the generic types capability in Chapter 14.
USING THE FINAL MODIFIER
You have already used the
final
keyword to fix the value of a static data member of a class. You can also
apply this keyword to the definition of a method, and to the definition of a class.
It may be that you want to prevent a subclass from overriding a method in your class. When this is the
case, simply declare that method as
final
. Any attempt to override a
final
method in a subclass results in
the compiler flagging the new method as an error. For example, you could declare the method
addPoint()
as
final
within the class
PolyLine
by writing its definition in the class as:
public final void addPoint(Point point) {
polyline.addItem(point); // Add the point to the list
}
Any class derived from
PolyLine
is not able to redefine this method. Obviously, an
abstract
method
cannot be declared as
final
— because it must be defined in a subclass somewhere.
If you declare a class as
final
, you prevent any subclasses from being derived from it. To declare the
class
PolyLine
as
final
, you define it as:
public final class PolyLine {
// Definition as before...
}
If you now attempt to define a class based on
PolyLine
, you get an error message from the compiler. An
abstract class cannot be declared as
final
because this prevents the abstract methods in the class from ever
being defined. Declaring a class as
final
is a drastic step that prevents the functionality of the class being
extended by derivation, so you should be very sure that you want to do this.
INTERFACES
In the classes that you derived from the class
Animal
, you had a common method,
sound()
, that was im-
plemented individually in each of the subclasses. The method signature was the same in each class, and the
method could be called polymorphically. The main point to defining the class
Animal
first and then subse-
quently defining the classes
Dog
,
Cat
, and so on, from it was to be able to get polymorphic behavior. When
all you want is a set of one or more methods to be implemented in a number of different classes so that you
can call them polymorphically, you can dispense with the base class altogether.
You can achieve the same result much easier by using a Java facility called an
interface
. The name indic-
ates its primary use — specifying a set of methods that represent a particular class interface, which can then
be implemented appropriately in a number of different classes. All of the classes then share this common
interface, and the methods in it can be called polymorphically through a variable of the interface type. This