/home/wpollock1/public_html/Java/Stock.java
// 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. The purpose was to highlight the constructor.
// (Since the class tracks the purchase date and price, it is
// closer to a StockLot class (you buy stocks in "lots").
//
// 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.
//
// Finally, note the fields declared as final. While not a realistic
// class, such a class is subject to various financial laws and
// regulations, which generally prohibit altering recorded transactions
// for any reason.
//
// Written 10/2008, updated 2017, 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 = (Date) datePurchased.clone();
}
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" );
this.currentPrice = newPrice;
this.priceDate = new Date();
}
public void setBroker ( String broker )
{
this.broker = broker;
}
}