I'm working on a program which states:
Create a Java Stock class to represent information about a stock that is bought and sold....Whenever the stock price is changed, the change in price per share is also updated. Omit the setter for the change in price per share. The change in price per share will only be set when price per share changes. Do not include a parameter for change in price in the constructor. Initialize the change to zero.
The only way I figured I could calculate the change in share price was to create a fourth variable (originalPrice), equate it to sharePrice, and subtract them. However, this is not working, and I am not sure how to create a "deep" copy for variables. Is there a way to make originalPrice a copy of sharePrice which can then be updated separately from sharePrice? Thank you for your help!
Stock class:
public class Stock {
private String name;
private double sharePrice;
private double originalPrice;
private double changeSharePrice = 0;
/**
* @param name
* @param sharePrice
* @param changeSharePrice
*/
public Stock(String stockName, double sharePrice) {
setName(stockName);
setSharePrice(sharePrice);
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String stockName) {
this.name = stockName;
}
/**
* @return the sharePrice
*/
public double getSharePrice() {
return sharePrice;
}
/**
* @param sharePrice the sharePrice to set
*/
public void setSharePrice(double sharePrice) {
this.sharePrice = sharePrice;
originalPrice = sharePrice;
changeSharePrice = sharePrice - originalPrice;
}
/**
* @return the changeSharePrice
*/
public double getChangeSharePrice() {
return changeSharePrice;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Stock Name: " + name + "/n Price Per Share: " + sharePrice + "/n Change in Price Per Share: "
+ changeSharePrice;
}
/*
* Copy Constructor
*/
public Stock(Stock other) {
name = other.name;
sharePrice = other.sharePrice;
changeSharePrice = other.changeSharePrice;
}
/*
* Deep copy method
*/
public Stock copy() {
return new Stock(name, sharePrice);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object) Equals Method
*/
public boolean equals(Object obj) {
Stock other = (Stock) obj;
if (name == other.name)
return true;
else
return false;
}
}
Here is my main:
public class tester {
public static void main(String[] args) {
// An object is created for Nomad Foods Limited
Stock one = new Stock("NOMD", 10.46);
//An object is created for Treehouse Foods
Stock two = new Stock("THS", 69.18);
one.setSharePrice(4.00);
System.out.print(one.getChangeSharePrice());
}
}