3

我正在做一个 Java 练习,但不知道我做错了什么。我创建了一个电影类(带有变量:评级、标题、movieId 和 FEE_AMT 的常量),然后扩展了该类:动作、喜剧和戏剧。这些派生类没有其他变量,只是不同的 FEE_AMT。

在电影(和派生类)中有一种计算滞纳金的方法:

/**
* 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);
}

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

现在我需要创建一个Rental类并main()创建一个类型为rental 类的数组来保存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;
}

这个方法调用:

/**
 * 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;
}

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

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

谢谢你。

4

1 回答 1

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 ...; }
于 2013-01-31T17:16:30.033 回答