In Example 3-4,
we declared our
Circle class to be part of a package named
shapes. Suppose we plan to implement a number of
Triangle, and so on. We can give these shape
classes our two basic
area( ) and
circumference() methods. Now, to make it easy to
work with an array of shapes, it would be helpful if all our shape
classes had a common superclass,
Shape. If we
structure our class hierarchy this way, every shape object,
regardless of the actual type of shape it represents, can be assigned
to variables, fields, or array elements of type
Shape. We want the
to encapsulate whatever features all our shapes have in common (e.g.,
methods). But our generic
doesn't represent any real kind of shape, so it
cannot define useful implementations of the methods. Java handles
this situation with abstract methods.
lets us define a method without implementing it by declaring the
method with the
abstract modifier. An
abstract method has no body; it simply has a
signature definition followed by a semicolon.
Here are the rules about
abstract methods and the
abstract classes that contain them:
Any class with an
abstract method is automatically
abstract itself and must be declared as such.
abstract class cannot be instantiated.
A subclass of an
abstract class can be
instantiated only if it overrides each of the
abstract methods of its superclass and provides ...