Java - overridden method not callable

I am working on a Java exercise and cannot figure out what I am doing wrong. I created a movie class (with variables: rating, title, movieId and a constant for FEE_AMT), and then extended the class: Action, Comedy and Drama. These derived classes have no other variables, just FEE_AMT.

In the movie (and derived classes), there is a method for calculating late payments:

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

      

If I just call the method directly with the object, for example: comedy1.calcLateFees(2)

- it will generate the correct amount of fees based on the different constant value in the derived method.

Now I needed to create a class Rental

, and then main()

create an array of the rental class type to store the rental objects (which consist of a Movie object, renterId and daysLate). Here is a method that takes an array of Rent objects and returns the late fees associated with the rent in the array:

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

      

and this method calls:

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

      

But the problem is that the method calcFees()

calls calcLateFees()

, but instead of calling the derived class, it calls the Movie class and returns the wrong amount.

I'm not sure if my problem is preventing the overridden method from being called calcLateFees()

.

Thank.

+3


source to share


1 answer


These derived classes have no other variables, just another FEE_AMT.

This is problem. Items are not polymorphic. What you need to do is turn FEE_AMT

into a method and override that method in derived classes.



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

      

+6


source







All Articles