Stock.java

Download Stock.java

 1: // Stock.java - A class whose objects represent stocks.
 2: // This class demonstrates constructors, getters, setters.
 3: // This is not a "production quality" class, which could keep
 4: // track of the exchange, use the Internet to get the current
 5: // price, etc.  The purpose was to highlight the constructor.
 6: //
 7: // Note how getDatePurchased returns a copy of datePurchased.
 8: // This is because (unlike Strings) Date objects are mutable.
 9: // If you return a reference to the date, it might get changed!
10: // This technique is called "making defensive copies".  You don't
11: // need to use it with immutable objects or primitives.
12: //
13: // Written 10/2008 by Wayne Pollock, Tampa Florida USA
14: 
15: import java.util.Date;
16: 
17: class Stock
18: {
19:    private final String symbol;
20:    private final String name;
21:    private final Date datePurchased;
22:    private final float initialPrice;  // price per share
23: 
24:    private float currentPrice;
25:    private Date priceDate;  // date when price last changed
26:    private String broker;  // Stock broker
27: 
28:    public Stock ( String symbol, String name, float price )
29:    {
30:       this.symbol = symbol;
31:       this.name = name;
32:       this.datePurchased = new Date();
33:       if ( price <= 0 )
34:          throw new IllegalArgumentException( "bad price" );
35:       this.initialPrice = price;
36:       this.priceDate = (Date) datePurchased.clone();
37:    }
38: 
39:    public String getSymbol () { return symbol; }
40:    public String getName () { return name; }
41:    public Date getDatePurchased () { return (Date) datePurchased.clone(); }
42:    public float getInitialPrice () { return initialPrice; }
43:    public float getCurrentPrice () { return currentPrice; }
44:    public String getBroker () { return broker; }
45: 
46:    public void setCurrentPrice ( float newPrice )
47:    {
48:       if ( newPrice <= 0 )
49:          throw new IllegalArgumentException( "bad price" );
50:       this.currentPrice = newPrice;
51:       this.priceDate = new Date();
52:    }
53: 
54:    public void setBroker ( String broker )
55:    {
56:       this.broker = broker;
57:    }
58: }