3

私は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);
}

たとえば、オブジェクトを使用してメソッドを完全に呼び出すとcomedy1.calcLateFees(2) 、派生メソッドの異なる定数値に基づいて正しい料金が生成されます。

ここで、クラスを作成し、レンタル オブジェクト (Movie オブジェクト、renterId、daysLate で構成される) を保持するためのタイプ Rental クラスの配列を作成する必要がRentalありmain()ました。次のメソッドは、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 に答える