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: // (Since the class tracks the purchase date and price, it is
 7: // closer to a StockLot class (you buy stocks in "lots").
 8: //
 9: // Note how getDatePurchased returns a copy of datePurchased.
10: // This is because (unlike Strings) Date objects are mutable.
11: // If you return a reference to the date, it might get changed!
12: // This technique is called "making defensive copies".  You don't
13: // need to use it with immutable objects or primitives.
14: //
15: // Finally, note the fields declared as final.  While not a realistic
16: // class, such a class is subject to various financial laws and
17: // regulations, which generally prohibit altering recorded transactions
18: // for any reason.
19: //
20: // Written 10/2008, updated 2017, by Wayne Pollock, Tampa Florida USA
21: 
22: import java.util.Date;
23: 
24: class Stock
25: {
26:    private final String symbol;
27:    private final String name;
28:    private final Date datePurchased;
29:    private final float initialPrice;  // price per share
30: 
31:    private float currentPrice;
32:    private Date priceDate;  // date when price last changed
33:    private String broker;  // Stock broker
34: 
35:    public Stock ( String symbol, String name, float price )
36:    {
37:       this.symbol = symbol;
38:       this.name = name;
39:       this.datePurchased = new Date();
40:       if ( price <= 0 )
41:          throw new IllegalArgumentException( "bad price" );
42:       this.initialPrice = price;
43:       this.priceDate = (Date) datePurchased.clone();
44:    }
45: 
46:    public String getSymbol () { return symbol; }
47:    public String getName () { return name; }
48:    public Date getDatePurchased () { return (Date) datePurchased.clone(); }
49:    public float getInitialPrice () { return initialPrice; }
50:    public float getCurrentPrice () { return currentPrice; }
51:    public String getBroker () { return broker; }
52: 
53:    public void setCurrentPrice ( float newPrice )
54:    {
55:       if ( newPrice <= 0 )
56:          throw new IllegalArgumentException( "bad price" );
57:       this.currentPrice = newPrice;
58:       this.priceDate = new Date();
59:    }
60: 
61:    public void setBroker ( String broker )
62:    {
63:       this.broker = broker;
64:    }
65: }