覆盖方法和使用超级

时间:2016-04-30 13:53:12

标签: java methods super overwrite

在我的委员会课程中,我试图从父类(每小时)覆盖付费方法来计算工作小时数的工资,我该怎么做?我的委员会和小时课程的代码是父母,在下面,覆盖发生在我把????

public class Commission extends Hourly
{
  double total_sales;
  double commission_rate;

  public Commission(String name, String address, String phone,
                    String soc_sec_number, double rate,double commission_rate)
  {
    super(  name,   address,   phone,
                      soc_sec_number,   rate);
    // set commission rate
     commission_rate = 0.02;
  }

  public void addSales (double sales)
  {
    sales += total_sales;

    /*????   */super.pay
  }

}

和每小时课程

// ********************************************************************
// Hourly.java       Java Foundations
//
// Represents an employee that gets paid by the hour
// ********************************************************************

public class Hourly extends Employee
{
  private int hours_worked;

  // -------------------------------------------------------------------------
  // Constructor: Sets up this hourly employee using the specified information
  // -------------------------------------------------------------------------
  public Hourly(String name, String address, String phone,
                String soc_sec_number, double rate)
  {
    super(name, address, phone, soc_sec_number, rate);
    hours_worked = 0;
  }

  // -----------------------------------------------------
  // Adds the specified number of hours to this employee's
  // accumulated hours
  // -----------------------------------------------------
  public void addHours(int more_hours)
  {
    hours_worked += more_hours;
  }

  // -----------------------------------------------------
  // Computes and returns the pay for this hourly employee
  // -----------------------------------------------------
  public double pay()
  {
    double payment = pay_rate * hours_worked;

    hours_worked = 0;
    return payment;
  }

  // ----------------------------------------------------------
  // Returns information about this hourly employee as a string
  // ----------------------------------------------------------
  public String toString()
  {
    return super.toString() + "\nCurrent hours: " + hours_worked;
  }
}

1 个答案:

答案 0 :(得分:0)

对于您的班级Commission,您可以像这样添加pay的覆盖:

@Override
public double pay() {
    double payment = super.pay();   // call the method of the parent
    ....                            // add other code
}