Java Reference
In-Depth Information
concrete state and behavior while leaving some abstract, without defined method
bodies. Such an entity is called an abstract class.
Abstract Class
A Java class that cannot be instantiated, but that instead serves as a super-
class to hold common code and declare abstract behavior.
You probably noticed a lot of redundancy between the Stock and MutualFund
code in the last section. For example, although the getMarketValue and getProfit
methods have identical code, they can't be moved up into the ShareAsset superclass
because they depend on the number of shares, which is different in each child class.
Ideally, we should get rid of this redundancy somehow.
There is also a problem with our current ShareAsset class. A ShareAsset isn't
really a type of asset that a person can buy; it's just a concept that happens to be rep-
resented in our code. It would be undesirable for a person to actually try to construct
a ShareAsset object—we wrote the class to eliminate redundancy, not for clients to
instantiate it.
We can resolve these issues by designating the ShareAsset class as abstract.
Writing abstract in a class's header will modify the class in two ways. First, the class
becomes noninstantiable, so client code will not be allowed to construct an object of
that type with the new keyword. Second, the class is enabled to declare abstract
methods without bodies. Unlike an interface, though, an abstract class can also
declare fields and implement methods with bodies, so the ShareAsset class can
retain its existing code.
The general syntax for declaring an abstract class is
public abstract class <name> {
...
}
Thus, our new ShareAsset class header will be
public abstract class ShareAsset {
...
}
An attempt to create a ShareAsset object will now produce a compiler error such
as the following:
ShareAsset is abstract; cannot be instantiated
ShareAsset asset = new ShareAsset("MSFT", 27.46);
1 error
 
Search WWH ::




Custom Search