Java Reference
In-Depth Information
3.7. Abstract Classes and Methods
An extremely useful feature of object-oriented programming is the
concept of the abstract class. Using abstract classes, you can declare
classes that define only part of an implementation, leaving extended
classes to provide specific implementation of some or all of the methods.
The opposite of abstract is concrete a class that has only concrete meth-
ods, including implementations of any abstract methods inherited from
superclasses, is a concrete class.
Abstract classes are helpful when some of the behavior is defined for
most or all objects of a given type, but other behavior makes sense only
for particular classes and not for a general superclass. Such a class is
declared abstract , and each method not implemented in the class is also
marked abstract . (If you need to define some methods but you don't
need to provide any implementation, you probably want to use inter-
faces, which are described in Chapter 4 . )
For example, suppose you want to create a benchmarking harness to
provide an infrastructure for writing benchmarked code. The class im-
plementation could understand how to drive and measure a benchmark,
but it couldn't know in advance which benchmark would be run. Most ab-
stract classes fit a pattern in which a class's particular area of expertise
requires someone else to provide a missing piecethis is commonly known
as the "Template Method" pattern. In many cases the expertise methods
are good candidates for being final so that the expertise cannot be com-
promised in any way. In this benchmarking example, the missing piece
is code that needs to be benchmarked. Here is what such a class might
look like:
abstract class Benchmark {
abstract void benchmark();
public final long repeat(int count) {
long start = System.nanoTime();
for (int i = 0; i < count; i++)
benchmark();
return (System.nanoTime() - start);
 
Search WWH ::




Custom Search