Java Reference
In-Depth Information
polar representation would not reap the same benefits we saw in our second imple-
mentation of TimeSpan , but it might make it easier for us to add certain functionality
to the Point class later.
8.5 Case Study: Designing a Stock Class
So far we have written several classes, but we have not talked about how to design a
class or how to break apart a programming problem into classes. In this section we'll
examine a larger programming problem and design a class and client to solve it. We
will create a class called Stock and a client program that compares the performance
of stocks that the user has purchased.
Consider the task of writing a financial program to record purchases of shares of
two stocks and report which has the greatest profit. The investor may have made sev-
eral purchases of the same Stock at different times and prices. The interaction with
the program might look like this:
First stock's symbol: AMZN
How many purchases did you make? 2
1: How many shares, at what price per share? 50 35.06
2: How many shares, at what price per share? 25 38.52
What is today's price per share? 37.29
Net profit/loss: $80.75
Second stock's symbol: INTC
How many purchases did you make? 3
1: How many shares, at what price per share? 15 16.55
2: How many shares, at what price per share? 10 18.09
3: How many shares, at what price per share? 20 17.15
What is today's price per share? 17.82
Net profit/loss: $29.75
AMZN was more profitable than INTC.
The program must perform several actions: prompting the user for input, calculat-
ing the amount spent on each purchase of stock, reporting profits, and so on. The
client program could perform all of these actions and could keep track of the finan-
cial data using existing types such as double s and String s. However, recall that we
began this chapter by talking about object-oriented reasoning. When you are studying
complex programs, it is often useful to think about the problem in terms of the rele-
vant objects that could solve it, rather than placing all behavior in the client program.
In this particular program, we must perform several computations that involve keep-
ing track of purchases of shares of a particular stock, so it would be useful to store
the purchase information in an object.
 
 
Search WWH ::




Custom Search