
Rahul S.
asked 05/14/22Java 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.
1 Expert Answer

Nicholas M. answered 06/10/22
The Tutor Who Knows What It's Like :)
1) replace " public class Rental" w/ " public abstract class Rental"
2) Rental will be your "super class", so to create a subclass you just do "class RegularRental extends Rental" and so on, and replace the current code w/ instances of that new subclass
3) simply create another getCharge() method inside of each subclass, but put "@Override" over it
4) create a Rental class, then a Movie class to go in that Rental Class, and then when you set the priceCode, that will determine which subclass it is and which version of getCharge() is called

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 further06/10/22
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Donald W.
Do you have a specific question about this problem?05/14/22