I wrote the following two classes (implementing a state pattern):
Price:
public abstract class Price {
public abstract double getAmount(int rentalDays);
public abstract int getPriceCode();
}
RegularPrice:
public class RegularPrice extends Price {
private static final int _priceCode = 0;
@Override
public double getAmount(int rentalDays) {
double res = 2;
if (rentalDays > 2)
res += (rentalDays - 2) * 1.5;
return res;
}
@Override
public int getPriceCode() {
return _priceCode;
}
}
The problem is that adding other subclasses of Price with differents _priceCode
translates into code duplication for the getPriceCode()
method.
I thought about pulling up the method to the superclass but then I couldn't declare _priceCode
private.
What's the standard solution?
I can't see any reasons why
getPriceCode()
has to stay in the derived class since it is a common behaviour to all subclasses, so put it the base class. So_priceCode
is inPrice
and not assigned and it should be declared as protected or package (depends if you want to let free access to it only from subclasses in the same package or even if from subclasses that belong to another package).Price
RegularPrice
In this way,
_priceCode
is directly visible only from subclasses of Price, from other parts of code it can be accessed only using the getter method andgetPriceCode()
is not duplicated.