设计一个Stock类和DividendStock类
- 编写了一个表示拥有股票情况的Stock类,这里给出了一个简化版,去掉了对参数的合法性的检查等细节:
- 现在,需要创建一个可以发放分红的股票。红利的多少和持有股票的数量成正比。不是所有的股票都会分红。所以不能直接在Stock类上直接增加这个功能。而是应该在Stock类的基础上,继承一个DividendStock类。并在这个子类中增加分红的属性和行为。
- (1).一个用于记录分红的字段dividents
- (2).重写父类的getProfit方法(在父类的getProfit方法的基础上还要加上分红的)
父类的getProfit+股票的总的分红(也就是字段dividents的值) - (3). 增加计算分红的方法,方法中的参数表示每股的红利,可以理解为成员变量dividents赋值: 股票的总的分红=每股的红利*总股数
public void payDividend(double amountPerShare) - 编写一个测试程序,创建一个名为”Oracle”的分红股票,先后以单价32元购买200股,以单价40元购买350股。每股分红2.8元。这支股票的当前价格是每股50元。
以下代码仅供参考
以下代码仅供参考
以下代码仅供参考
/** *作者:魏宝航 *2020年11月22日,下午15:40 */ public class test { public static void main(String[] args) { DividendStock oracle = new DividendStock("Oracle"); oracle.purchase(200,32); oracle.purchase(350,40); oracle.payDividend(2.8); System.out.println(oracle.toString()); System.out.println(oracle.getProfit(50)); } } class Stock { private String symbol; private int totalShares; private double totalCost; public Stock(){ } // Initializes a new Stock with no shares purchased. public Stock(String theSymbol) { symbol = theSymbol; totalShares = 0; totalCost = 0.0; } // Returns the total shares purchased of this stock. public int getTotalShares() { return totalShares; } // Returns the total profit or loss earned on this stock. public double getProfit(double currentPrice) { double marketValue = totalShares * currentPrice; return marketValue - totalCost; } // Records purchase of the given shares at the given price. public void purchase(int shares, double pricePerShare) { totalShares += shares; totalCost += shares * pricePerShare; } @Override public String toString() { return "Stock [symbol=" + symbol + ", totalShares=" + totalShares + ", totalCost=" + totalCost + "]"; } //getter和setter方法自己补充 public void setTotalCost(double totalCost) { this.totalCost = totalCost; } public void setTotalShares(int totalShares) { this.totalShares = totalShares; } public void setSymbol(String symbol) { this.symbol = symbol; } public double getTotalCost() { return totalCost; } public String getSymbol() { return symbol; } } class DividendStock extends Stock{ double dividents; public DividendStock(String symbol){ super(symbol); } @Override public double getProfit(double currentPrice) { return super.getProfit(currentPrice)+dividents; } public void payDividend(double amountPerShare){ dividents=super.getTotalShares()*amountPerShare; } @Override public String toString() { return "Stock [symbol=" + super.getSymbol() + ", totalShares=" + super.getTotalShares() + ", totalCost=" + super.getTotalCost() +", dividents="+dividents+ "]"; } }