The Stock Class Part I Write a class called Stock that repre

The Stock Class Part I Write a class called Stock that represents a stock object consisting of a stock symbol, the total number of shares owned, and the total cost. Think about an appropriate type for each piece of data. Astock object should have the following methods. Remember to follow the conventions for encapsulated your data. (i.e. your fields should be private). public stock (string symbol) Constructs a new Stock object with the given symbol. What is the initial value for total shares and total cost? public string getsymbol Returns the symbol of this stock; for example, \"AMZN\" for Amazon. public int get TotalShares Returns the number of shares owned for this stock object. public double get TotalCost Returns the total amount paid for the stock. public void purchase (int shares, double price Per Share) Records the purchase of the given shares at the given price public double get Profit (double current Price) Returns the total profit or loss earned on this stock based on the given price per share. public string to String Returns a String representation of this stock with the stock symbol, the number of shares, and the total cost paid for the stock. Part 2 write a client program with a main method to test your Dwtk

Solution

public class Stock{
    private String symbol;
    private int totalShares;
    private double totalCost;

    public Stock(String symbol){
        this.symbol = symbol;
        this.totalShares = 0;
        this.totalCost = 0;
    }

    public String getSymbol(){
        return this.symbol;
    }

    public int getTotalShares(){
        return this.totalShares;
    }

    public double getTotalCost(){
        return this.totalCost;
    }

    public void purchase(int shares, double pricePerShare){
        this.totalShares += shares;
        this.totalCost += pricePerShare*shares;
    }

    public double getProfit(double currentPrice){
        return this.totalShares*currentPrice - this.totalCost;
    }

    public String toString(){
        return \"Symbol: \" + this.symbol + \"\\tTotal Shares: \" + this.totalShares + \"\\tTotal Cost: \" + this.totalCost;
    }

    public static void main(String[] args) {
        Stock stock1 = new Stock(\"YHOO\");
        stock1.purchase(20, 10);
        stock1.toString();

        stock1.purchase(20, 30);
        stock1.toString();

        stock1.purchase(10, 20);
        stock1.toString();

        System.out.println(\"Profit: \"+ stock1.getProfit(22));
    }
}

 The Stock Class Part I Write a class called Stock that represents a stock object consisting of a stock symbol, the total number of shares owned, and the total
 The Stock Class Part I Write a class called Stock that represents a stock object consisting of a stock symbol, the total number of shares owned, and the total

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site