Java Reference
In-Depth Information
Classes
You finalize classes by using the
final
modifier in the declaration for the class, as in the
following:
public final class ChatServer {
// body of method
}
A
final
class cannot be subclassed by another class. As with
final
methods, this
process introduces some speed benefits to the Java language at the expense of flexibility.
If you're wondering what you're losing by using final classes, you must not have tried to
subclass something in the Java class library yet. Many of the popular classes are final,
such as
java.lang.String
,
java.lang.Math
, and
java.net.URL
. If you want to create a
class that behaves like strings but with some new changes, you can't subclass
String
and
define only the behavior that is different. You have to start from scratch.
All methods in a final class automatically are final themselves, so you don't have to use a
modifier in their declarations.
Because classes that can provide behavior and attributes to subclasses are much more
useful, you should strongly consider whether the benefit of using
final
on one of your
classes is outweighed by the cost.
In a class hierarchy, the higher the class, the more abstract its definition. A class at the
top of a hierarchy of other classes can define only the behavior and attributes common to
all the classes. More specific behavior and attributes are going to fall somewhere lower
down the hierarchy.
When you are factoring out common behavior and attributes during the process of defin-
ing a hierarchy of classes, you might at times find yourself with a class that doesn't ever
need to be instantiated directly. Instead, such a class serves as a place to hold common
behavior and attributes shared by their subclasses.
These classes are called
abstract classes
, and they are created using the
abstract
modi-
fier. The following is an example:
public abstract class Palette {
// ...
}