![](/img/trans.png)
[英](OOP/Java) How should I handle this subclass-superclass relationship?
[英]Java - subclass and superclass relationship
我正在為我的 Java 課程做作業,但我完全迷失了。 我想我並不完全理解子類和超類的關系,但我正在盡我最大的努力前進。 作業要求我們這樣做:
Stock.java 類代表購買的給定股票的股票。 您想為支付股息的股票創建一種類型的對象。
每個股東收到的股息金額與該人擁有的股份數量成正比。 並非每只股票都會派發股息,因此您不希望將此功能直接添加到 Stock 類。 相反,您應該創建一個名為 DividendStock 的新類,它擴展 Stock 並添加此新行為。
每個 DividendStock 對象都將從 Stock 超類繼承代碼、總份額和總成本。 您需要添加一個字段來記錄支付的股息金額。
記錄的股息支付應被視為股東的利潤。 DividendStock 的總利潤等於股票價格的利潤加上任何股息。 該金額計算為市場價值(股票數量乘以當前價格)減去為股票支付的總成本,加上支付的股息金額。
這是 stock.java 文件
/**
* A Stock object represents purchases of shares of a
* company's stock.
*
*/
public class Stock {
private String symbol;
private int totalShares;
private double totalCost;
/**
* Initializes a new Stock with no shares purchased
* @param symbol = the symbol for the trading shares
*/
public Stock(String symbol) {
this.symbol = symbol;
totalShares = 0;
totalCost = 0.0;
}
/**
* Returns the total profit or loss earned on this stock
* @param currentPrice = the price of the share on the stock exchange
* @return
*/
public double getProfit(double currentPrice) {
double marketValue = totalShares * currentPrice;
return marketValue - totalCost;
}
/**
* Record purchase of the given shares at the given price
* @param shares = the number of shares purchased
* @param pricePerShare = the price paid for each share of stock
*/
public void purchase(int shares, double pricePerShare) {
totalShares += shares;
totalCost += shares * pricePerShare;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public int getTotalShares() {
return totalShares;
}
public void setTotalShares(int totalShares) {
this.totalShares = totalShares;
}
public double getTotalCost() {
return totalCost;
}
public void setTotalCost(double totalCost) {
this.totalCost = totalCost;
}
}
我已經開始研究一個名為 DividendStock.java 的子類,但我不確定我缺少什么以及我需要做些什么來實際測試它是否有效。 有沒有人有任何提示?
public class DividendStock extends Stock{
private double dividends;
private double profit;
public DividendStock(String symbol){
super(symbol);
dividends = 0.0;
profit = 0.0;
}
public double payDividend(double amountPerShare){
dividends += amountPerShare*getTotalShares();
return dividends;
}
public double profit(double amountPerShare) {
profit = super.getProfit(profit) + payDividend(amountPerShare);
return profit;
}
}
一個提示,如果你不理解它,請保持簡單,這樣你才能最好地學習它。 這是一個適合您的工作示例。
class MySuperClass {
protected String whoami;
MySuperClass() {
this.whoami = "I'm the Superclass";
}
void whoAmI() {
System.out.println(whoami);
}
}
class MySubClass extends MySuperClass {
MySubClass() {
super.whoami = "I'm the Subclass";
}
}
public class TestWorld {
public static void main(String[] args) {
MySuperClass bigbro = new MySuperClass();
MySubClass littlesis = new MySubClass();
bigbro.whoAmI();
littlesis.whoAmI();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.