Java Reference
In-Depth Information
per share must not be negative numbers. To perform this test, we can insert the fol-
lowing lines at the start of our
purchase
method:
if (shares < 0 || pricePerShare < 0) {
throw new IllegalArgumentException();
}
Next, we'll write the body of the
getProfit
method. As we noted previously, the
profit of a
Stock
is equal to its current market value minus the amount that was paid
for it:
profit
((total shares)
*
(current share price))
(total cost)
We can implement this formula in a straightforward manner using the
totalShares
and
totalCost
fields and the
currentPrice
parameter:
// Returns the total profit or loss earned on this stock,
// based on the given price per share.
public double getProfit(double currentPrice) {
return totalShares
*
currentPrice - totalCost;
}
Note that parentheses are not needed in the code because multiplication has a
higher precedence than subtraction.
As we did for the other methods, we should check for illegal parameter values. In
this case, we shouldn't allow a negative current price per share. To ensure that this
doesn't happen, we can place the following code at the start of the method:
if (currentPrice < 0.0) {
throw new IllegalArgumentException();
}
After we've written all the fields, the constructor, and the methods of our
Stock
,
the class will look like this:
1 // A Stock object represents purchases of shares of a stock.
2
3
public class
Stock {
4
private
String symbol; // stock symbol, e.g. "YHOO"
5
private int
totalShares; // total shares purchased
6
private double
totalCost; // total cost for all shares
7
8 // initializes a new Stock with no shares purchased
9 // pre: symbol != null
Search WWH ::
Custom Search