Java Reference
In-Depth Information
Stock Method and Constructor Implementation
Now that we've decided on some of the Stock 's state and behavior, let's think about
how to construct Stock objects. The client program will need the ability to create
two Stock s and record purchases of them.
It may be tempting to write a constructor that accepts three parameters: the sym-
bol, the total number of shares purchased, and the total cost. But our Stock objects
are accumulators of purchases, and we may want to be able to create new Stock
objects before the program records initial purchases. Let's design our class to require
only the symbol as a parameter and initialize the other fields to 0 :
// initializes a new Stock with no shares purchased
public Stock(String theSymbol) {
symbol = theSymbol;
totalShares = 0;
totalCost = 0.0;
}
When a constructor takes an object as a parameter (such as the String
theSymbol ), it might make sense to check that parameter's value to make sure it isn't
null . One possible way to handle this case would be to throw an exception if a null
symbol is passed when the program creates a Stock object. We could do this by
inserting the following lines at the start of the Stock 's constructor:
if (theSymbol == null) {
throw new NullPointerException();
}
Sun recommends that you throw a NullPointerException when a parameter's
value is null but should not be. For other invalid parameter values, throw an
IllegalArgumentException .
Now let's write the body of the purchase method. The task of recording the pur-
chase consists of adding the new number of shares to the total number of shares and
adding the new price paid for these shares to the total cost. The price paid is equal to
the number of shares times the price per share. Here's the code for the purchase
method to implement this behavior:
// records a purchase of the given number of shares of this stock
// at the given price per share
public void purchase(int shares, double pricePerShare) {
totalShares += shares;
totalCost += shares * pricePerShare;
}
It might make sense here to check the parameters passed in to make sure they are
valid, as we did with the constructor. In this case, valid numbers of shares and prices
 
Search WWH ::




Custom Search