Java Reference
In-Depth Information
As the program illustrates, all subclasses of
TwoDShape
must
override
area( )
. To prove
this to yourself, try creating a subclass that does not override
area( )
. You will receive
a compile-time error. Of course, it is still possible to create an object reference of type
TwoDShape
, which the program does. However, it is no longer possible to declare objects
of type
TwoDShape
. Because of this, in
main( )
the
shapes
array has been shortened to 4,
and a
TwoDShape
object is no longer created.
One last point: Notice that
TwoDShape
still includes the
showDim( )
and
getName( )
methods and that these are not modified by
abstract
. It is perfectly acceptable—indeed,
quite common—for an abstract class to contain concrete methods which a subclass is free
to use as is. Only those methods declared as
abstract
need be overridden by subclasses.
Using final
As powerful and useful as method overriding and inheritance are, sometimes you will want
to prevent them. For example, you might have a class that encapsulates control of some
hardware device. Further, this class might offer the user the ability to initialize the device,
making use of private, proprietary information. In this case, you don't want users of your
class to be able to override the initialization method. Whatever the reason, in Java it is easy
to prevent a method from being overridden or a class from being inherited by using the
keyword
final
.
final Prevents Overriding
To prevent a method from being overridden, specify
final
as a modifier at the start of its
declaration. Methods declared as
final
cannot be overridden. The following fragment illus-
trates
final
: