Java - 重写方法未被调用

Kir*_*k B 3 java class derived

我正在进行Java练习,无法弄清楚我做错了什么.我创建了一个Movie类(带有变量:rating,title,movieId和FEE_AMT的常量),然后使用:Action,Comedy和Drama扩展了类.这些派生类没有其他变量,只有不同的FEE_AMT.

在Movie(和派生类)中,有一种方法可以计算到期的滞纳金:

/**
* Returns the late fee due on a Movie rental
*   @param  days the number of days for late fee calculations
*   @return   true or false depending on the evaluation of the expression
**/ 
public double calcLateFees(int days){
    return(days * FEE_AMT);
}
Run Code Online (Sandbox Code Playgroud)

如果我只是直接用对象调用方法,例如:comedy1.calcLateFees(2) - 它将根据派生方法中的不同常量值生成正确的费用金额.

现在我需要创建一个Rental类并main()创建一个类型租赁类的数组来保存Rental对象(由Movie对象,renterId和daysLate组成).以下是接收Rental对象数组的方法,并返回数组中所有租借的滞纳金:

/**
 * lateFeesOwed returns the amount of money due for late fees on all movies 
 *  which are located in an array of Rentals.
 *
 *  @return feeDue the amount of money due for late fees.
 */
public static double lateFeesOwed(Rental[] rentalArray){
    double feeDue = 0;

    for(int i = 0; i < rentalArray.length; i++)
    {
        feeDue += rentalArray[i].calcFees();  //This is part of the problem??

    }

    return feeDue;
}
Run Code Online (Sandbox Code Playgroud)

这个方法调用:

/**
 * CalcFees returns the amount of money due for late fees on a movie rental.
 *
 *  @return feeDue the amount of money due for late fees.
 */
public double calcFees(){
  double feeDue = rentalName.calcLateFees(this.daysLate);  
  return feeDue;
}
Run Code Online (Sandbox Code Playgroud)

但问题是该calcFees()方法正在调用,calcLateFees()而不是调用派生类,它调用Movie类并返回不正确的数量.

我不确定我的问题在哪里阻止被覆盖的方法calcLateFees()被调用.

谢谢.

NPE*_*NPE 6

这些派生类没有其他变量,只有不同的FEE_AMT.

这就是问题.数据成员不是多态的.您需要做的是FEE_AMT转换为方法,并在派生类中重写该方法.

// Movie

public double calcLateFees(int days){
    return(days * getFeeAmt());
}

protected abstract double getFeeAmt(); // or implement if you wish

// Action etc

@Override
protected double getFeeAmt() { return ...; }
Run Code Online (Sandbox Code Playgroud)

  • 太快了! (2认同)