如何重写子类中的方法?

2023-12-05

我编写了一个库存程序,其中包含一个数组和一个方法来计算输入的所有库存项目的总成本。我现在必须包含一个子类来覆盖原来的子类以包含“一个独特的功能”。我创建了一个名为 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
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何重写子类中的方法? 的相关文章

随机推荐