如何覆盖子类中的方法?

时间:2011-03-07 03:44:05

标签: java class methods override

我编写了一个库存程序,其中包含一个数组和一个方法来计算输入的所有库存项目的总成本。我现在必须包含一个覆盖原始的子类,以包含“一个独特的功能”。我创建了一个名为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;
    }

}

1 个答案:

答案 0 :(得分: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
    }
}