계산기 만들기 Lv3를 진행하면서 요구사항에 제네릭과 Enum을 사용하라고 되어있었다. Enum은 강의 및 인터넷을 통해 어느정도 이해를 했지만 제네릭에관에서는 감이 잡히질 않았다. 그래서 튜터님과의 상담을 통해 이를 알게 되었고 바로 적용해 보았다.
제네릭을 사용하여 클래스 구현
public class ArithmeticCalculator<T extends Number> {
// calculator 클래스에 T로 선어되어있는 클래스는 반드시 넘버를 상속받은 클래스여야 한다.
private final List<Double> results = new ArrayList<>();
public void calculate(T num1, T num2, OperatorType operator) {
double operand1 = num1.doubleValue();
double operand2 = num2.doubleValue();
double result = 0;
switch (operator) {
case ADD:
result = operand1 + operand2;
break;
case MINUS:
result = operand1 - operand2;
break;
case MULTIPLY:
result = operand1 * operand2;
break;
case DIVIDE:
if (operand2 == 0) {
throw new ArithmeticException("0 으로는 나눌수 없습니다.");
}
result = operand1 / operand2;
break;
}
results.add(result);
System.out.println("결과: " + result);
}
...
나는 ArithemticCalculator 클래스를 작성하면서, 제네릭을 사용하여 연산에 사용되는 숫자의 타입을 T로 지정하고, 이름 Number 클래스 또는 이를 상속하는 클래스에서 사용할 수 있도록 처리하였고 이렇게 하면 정수(Integer), 실수(Double), Long 등 다양한 숫자 타입을 처리 할 수있어 요구 사항에 맞게 처리 할 수 있었다.