【问题标题】:Java - overridden method not getting calledJava - 未被调用的覆盖方法
【发布时间】:2013-01-31 17:14:12
【问题描述】:

我正在做一个 Java 练习,但不知道我做错了什么。我创建了一个电影类(带有变量:等级、标题、电影 ID 和 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() 被调用。

谢谢。

【问题讨论】:

    标签: java class derived


    【解决方案1】:

    这些派生类没有其他变量,只是不同的 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 ...; }
    

    【讨论】:

    • +1,我需要阅读整本书两次,然后才知道这里已经有答案了..:P
    猜你喜欢
    • 2011-12-13
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多