// Stock.java - A class whose objects represent stocks. // This class demonstrates constructors, getters, setters. // This is not a "production quality" class, which could keep // track of the exchange, use the Internet to get the current // price, etc. // // Note how getDatePurchased returns a copy of datePurchased. // This is because (unlike Strings) Date objects are mutable. // If you return a reference to the date, it might get changed! // This technique is called "making defensive copies". You don't // need to use it with immutable objects or primitives. // // Written 10/2008 by Wayne Pollock, Tampa Florida USA import java.util.Date; class Stock { private final String symbol; private final String name; private final Date datePurchased; private final float initialPrice; // price per share private float currentPrice; private Date priceDate; // date when price last changed private String broker; // Stock broker public Stock ( String symbol, String name, float price ) { this.symbol = symbol; this.name = name; this.datePurchased = new Date(); if ( price <= 0 ) throw new IllegalArgumentException( "bad price" ); this.initialPrice = price; this.priceDate = datePurchased; } public String getSymbol () { return symbol; } public String getName () { return name; } public Date getDatePurchased () { return (Date) datePurchased.clone(); } public float getInitialPrice () { return initialPrice; } public float getCurrentPrice () { return currentPrice; } public String getBroker () { return broker; } public void setCurrentPrice ( float newPrice ) { if ( newPrice <= 0 ) throw new IllegalArgumentException( "bad price" ); currentPrice = newPrice; priceDate = new Date(); } public void setBroker ( String broker ) { this.broker = broker; } }