![](/img/trans.png)
[英]My generic superclass method returns a List of subclass elements how do I Override this method in decendent class to return a List of the subclass
[英]How do I override a method in a subclass?
我編寫了一個清單程序,以包括一個數組和一種方法來計算輸入的所有清單項目的總成本。 現在,我必須包含一個覆蓋原始類的子類,以包含“一個獨特功能”。 我創建了一個名為ItemDetails的新文件,以設置原始Item的子類。 我需要包含一個獨特功能,並計算庫存價值,並計算此子類中的5%的進貨費用。 我只是將一些相關的代碼轉移到另一個類中嗎? 還是我寫兩次代碼? 我不知道下一步該怎么做。 任何幫助都是有用的。 謝謝。 這是我到目前為止的內容:
package inventory3;
public class ItemDetails extends Items
{
public static void override()
{
private String Name;
private double pNumber, Units, Price;
public ItemDetails()
{
}
}
}
這是應該覆蓋的Item類文件:
package inventory3;
import java.lang.Comparable;
public class Items implements Comparable
{
private String Name;
private double pNumber, Units, Price;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
public int compareTo(Object item)
{
Items tmp = (Items) item;
return this.getName().compareTo(tmp.getName());
}
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public static double getCombinedCost(Items[] item)
{
double combined = 0;
for(int i =0; i < item.length; ++i)
{
combined = combined + item[i].calculateTotalPrice();
}
return combined;
}
}
您只需聲明一個與父類中的方法具有相同簽名的方法。 所以你的樣子:
package inventory3;
public class ItemDetails extends Items {
private String Name;
private double pNumber, Units, Price;
public ItemDetails(String Name, double pNumber, double Units, double Price) {
this.Name = Name;
this.pNumber = pNumber;
this.Units = Units;
this.Price = Price;
}
// getters and setters....
// The @Override is optional, but recommended.
@Override
public double calculateTotalPrice() {
return Units * Price * 1.05; // From my understanding this is what you want to do
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.