Java Reference
In-Depth Information
Really, the
Employee
class introduced earlier in this chapter should also have been
an abstract class. We did not especially want client code to construct
Employee
objects. No one is
just
an employee; the
Employee
class merely represented a general
category that we wanted the other classes to extend.
Abstract classes are allowed to implement interfaces. Rather than requiring all
subclasses of
ShareAsset
to implement the
Asset
interface, we can specify that
ShareAsset
implements
Asset
:
public abstract class ShareAsset implements Asset {
...
}
This indication will save
ShareAsset
subclasses from having to write
implements
Asset
in their class headers.
ShareAsset
does not implement the
getMarketValue
method required by
Asset
; that functionality is left for its subclasses. We can instead declare
getMarketValue
as an abstract method in the
ShareAsset
class. Abstract methods
declared in abstract classes need to have the keyword
abstract
in their headers in
order to compile properly. Otherwise, the syntax is the same as when we declare an
abstract method in an interface, with a semicolon replacing the method's body:
// returns the current market value of this asset
public abstract double getMarketValue();
The general syntax for an abstract method declaration in an abstract class is the
following:
public abstract <type> <name> (<type> <name>, ..., <type> <name>);
Another benefit of this design is that code in the abstract class can actually call
any of its abstract methods, even if they don't have implementations in that file. This
is allowed because the abstract class can count on its subclasses to implement the
abstract methods. Now that
ShareAsset
implements
Asset
, we can move the
common redundant
getProfit
code up to
ShareAsset
and out of
Stock
and
MutualFund
:
// returns the profit earned on shares of this asset
public double getProfit() {
// calls an abstract getMarketValue method
// (the subclass will provide its implementation)
return getMarketValue() - totalCost;
}
ShareAsset
objects can call
getMarketValue
from their
getProfit
methods
even though that method isn't present in
ShareAsset
. The code compiles because
Search WWH ::
Custom Search