Rahul S.

asked • 05/14/22

Java Refactoring code

Refactoring question

Consider the following code for 2 classes: Rental and Movie

 

 public class Rental {

  private Movie movie;

 private int daysRented;

  public Rental(Movie movie, int daysRented){

    this.movie = movie;

     this.daysRented = daysRented;

  }

}

 

 


public double getCharge(){

  double thisAmount = 0;

  switch(movie.getPriceCode()){

    case Movie.REGULAR:

      thisAmount +=2

      if(daysRented > 2){

        thisAmount+= (daysRented-2) + 15;

      }

    case Movie.NEWRELEASE:

      thisAmount += daysRented + 3;

      break;

    case Movie.CHILDREN:

      thisAmount += 1.5;

      if(daysRented > 3){

        thisAmount += (daysRented - 3) * 1.5;

      }

    return thisAmount;

  }

}

 

public class Movie{

  public static final int CHILDREN = 2;

  public static final int REGULAR = 0;

  public static final int NEWRELEASE = 1;

  private String title;

  private int priceCode;

  public Movie(String title, int priceCode){

    title = title;

    priceCode = priceCode;

  }

  public int getPriceCode(){

    return priceCode;

  }

  public void setPriceCode(int arg){

    priceCode = arg;

  }

  public String getTitle(){

    return title;

  }

}

 

Refactor this code to remove the multipart conditional in getCharge() and re-write using the following suggestions:

1) make Rental class abstract and make getCharge() an abstract method.

2) create 3 concrete subclasses childrenRental, RegularRental and NewReleaseRental for Rental class.

3) Override getCharge() in each of the subclasses.

4) write code to create an instance of Movie with title "Avengers" and daysRented = 4 and set priceCode to be REGULAR and call the getCharge method for this rental.


Donald W.

Do you have a specific question about this problem?
Report

05/14/22

Rahul S.

Yes How can I rewrite it according to the conditions provided.
Report

05/15/22

Donald W.

The problem already lists 4 explicit steps. Have you tried following those steps? Which step are you stuck on? What problems did you run into?
Report

05/15/22

1 Expert Answer

By:

Nicholas M. answered • 06/10/22

Tutor
New to Wyzant

The Tutor Who Knows What It's Like :)

Nicholas M.

better way to look at it is: 1) google how to make an abstract class w/ an abstract method 2) google how to create sub classes 3) google how to override a method in a sub class 4) put it all together, which we can set up a meeting to discuss further
Report

06/10/22

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.