TroubleShooting
객체 속성 ArrayList에서 발생할 수 있는 오류 - 생성자 문제
서한성
2022. 7. 3. 20:36
Customer class
package chap8.inheritance.inheritanceExample;
import java.util.ArrayList;
public class Customer {
int customerId;
String customerName;
String customerGrade;
int bonusPoint;
double bonusRatio;
ArrayList<Coupon> couponList;
public Customer(int customerId, String customerName) {
this.customerId = customerId;
this.customerName = customerName;
this.bonusRatio = 0.01;
this.customerGrade = "SILVER";
}
public void bonusAdd(Product product) {
bonusPoint += product.price * bonusRatio;
if (customerGrade.equals("SILVER")) {
couponList.add(new Coupon("SILVER Coupon"));
} else if (customerGrade.equals("VIP")) {
couponList.add(new Coupon("VIP Coupon"));
}
}
public void showCustomerInfo() {
System.out.println(customerName + "님의 포인트는 " + bonusPoint + "p 입니다.");
System.out.println(customerName + "님의 보유 쿠폰은 ");
for (int i = 0; i < couponList.size(); i++) {
System.out.println(couponList.get(i).couponName);
}
System.out.println("입니다.");
}
}
VIPCustomer class
package chap8.inheritance.inheritanceExample;
import java.util.ArrayList;
public class VIPCustomer extends Customer {
ArrayList<Coupon> couponList;
public VIPCustomer(int customerId, String customerName) {
super(customerId, customerName);
this.bonusRatio = 0.05;
this.customerGrade = "VIP";
}
}
Product는 아이디와 이름, Coupon은 이름을 속성으로 갖는다.
일반등급(실버)는 포인트 적립율 1%, VIP등급은 적립율 5%를 적용하고
Product 구매 시 적립율에 따라 포인트가 적립되고 실버는 실버쿠폰, VIP는 VIP 쿠폰이 발행된다.
Customer는 쿠폰 속성을 ArrayList로 갖도록 선언했는데, 이때 main 메소드를 만들어 실행해보면

다음과 같이 NullPointerException이 발생한다.
디버깅을 통해 이유를 찾아보았다.

처음에는 쿠폰 add에 쿠폰 객체가 들어가지 않아 null값이 되어 발생하는 문제인 줄 알았는데 자세히 보니
couponList 자체가 null이기 때문에 할당할 공간이 없어서 발생하는 문제였다.
그래서 Customer생성자를 다음과 같이 수정했다.
public Customer(int customerId, String customerName) {
this.customerId = customerId;
this.customerName = customerName;
this.bonusRatio = 0.01;
this.customerGrade = "SILVER";
this.couponList = new ArrayList<>();
}
이렇게 해서 Customer 객체가 생성될 때 couponList가 생성되게 하여 문제를 해결했다.
