如何覆盖子类中的方法?

g3n*_*0st 1 java methods overriding class

我有一个库存程序,包括一个数组和一个方法来计算输入的所有库存项目的总成本.我现在必须包含一个覆盖原始的子类,以包含"一个独特的功能".我创建了一个名为ItemDetails的新文件来设置原始Item的子类.我需要包含一个独特的功能并计算库存的价值,并在此子类中计算5%的重新进货费用.我只是将一些相关的线路转移到另一个班级吗?或者我写两次代码?我不知道接下来该做什么.任何帮助都很有用.谢谢.这是我到目前为止:

package inventory3;

public class ItemDetails extends Items
{
public static void override()
    {
    private String Name;
    private double pNumber, Units, Price;

public ItemDetails()
        {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是它应该覆盖的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;
    }

}
Run Code Online (Sandbox Code Playgroud)

Pet*_*r C 5

您只需声明一个方法,该方法与父类中的方法具有相同的签名.所以你的看起来像:

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
    }
}
Run Code Online (Sandbox Code Playgroud)