Java Reference
In-Depth Information
implement the
deductFees
method, and the new account would inherit the
do-nothing method of the superclass. There is a better wayȌdeclare the
deductFees
method as an abstract method:
public
abstract
void deductFees();
An abstract method has no implementation. This forces the implementors of
subclasses to specify concrete implementations of this method. (Of course, some
subclasses might decide to implement a do-nothing method, but then that is their
choiceȌnot a silently inherited default.)
An abstract method is a method whose implementation is not specified.
You cannot construct objects of classes with abstract methods. For example, once
the
BankAccount
class has an abstract method, the compiler will flag an attempt
to create a
new BankAccount()
as an error. Of course, if the
CheckingAccount
subclass overrides the
deductFees
method and supplies
an implementation, then you can create
CheckingAccount
objects.
An abstract class is a class that cannot be instantiated.
A class for which you cannot create objects is called an abstract class. A class for
which you can create objects is sometimes called a concrete class. In Java, you
must declare all abstract classes with the keyword
abstract
:
public
abstract
class BankAccount
{
public abstract void deductFees();
. . .
}
460
461
A class that defines an abstract method, or that inherits an abstract method without
overriding it, must be declared as abstract. You can also declare classes with no
abstract methods as abstract. Doing so prevents programmers from creating
instances of that class but allows them to create their own subclasses.
Note that you cannot construct an object of an abstract class, but you can still have
an object reference whose type is an abstract class. Of course, the actual object to
which it refers must be an instance of a concrete subclass: