What is Abstract Class:
It is a class that contains one or more abstract methods.
Why use Abstract Class:
For resuseability code.
When you want to create a class that is similar to another class.
-> You can delete duplicate codes.
-> You don't have to modify original class.
-> You can use parent class code in child class.
How to use Abstract Class:
Maek an abstract class.
Use extends for inherirance.
Implement abstract methods of the parent class in child class
When you want to modify or implement the methods of the parent class, write @Override annotation on the method.
Parent Class
public abstract class DiscountPolicy {
private List<DiscountCondition> conditions = new ArrayList<>();
public DiscountPolicy(DiscountCondition ... conditions) {
this.conditions = Arrays.asList(conditions);
}
public Money calculateDiscountAmount(Dish dish) {
for (DiscountCondition each : conditions) {
if(each.isSatisfiedBy(dish)) {
return getDiscountAmount(dish);
}
}
return Money.ZERO;
}
abstract protected Money getDiscountAmount(Dish dish);
}
Child Class
public class AmountDiscountPolicy extends DiscountPolicy {
private Money discountAmount;
public AmountDiscountPolicy(Money discountAmount, DiscountCondition ... conditions) {
super(conditions);
this.discountAmount = discountAmount;
}
@Override
protected Money getDiscountAmount(Dish dish) {
return discountAmount;
}
}
Child Class
public class PercentDiscountPolicy extends DiscountPolicy {
private double percent;
public PercentDiscountPolicy(double percent, DiscountCondition ... conditions) {
super(conditions);
this.percent = percent;
}
@Override
protected Money getDiscountAmount(Dish dish) {
return dish.getDishFee();
}
}
Reference: Object book
chapter2 Object-Oriented Programming
댓글