![](/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.