데이터클래스
멤버변수만 존재하는 클래스
기능(인스턴트 메소드)이 없는 클래스
Java 14 버전 미만의 데이터 클래스
public class Coffee { String name; int price; public Coffee(String name, int price) { this.name = name; this.price = price; } }
Java 14 버전 이후의 데이터 클래스
public record Coffee(String name, int price) { }
// CoffeeShop 클래스의 멤버변수를 Coffee로 변경
public class Coffee {
String name;
int price;
public Coffee(String name, int price) {
this.name = name;
this.price = price;
}
}
public class CoffeeShop {
Coffee iceAmericano;
Coffee hotAmericano;
public CoffeeShop(Coffee iceAmericano, Coffee hotAmericano) {
this.iceAmericano = iceAmericano; // 초기값 할당
this.hotAmericano = hotAmericano; // 초기값 할당
}
public int orderCoffee(int menu, int quantity) {
if (menu == 1) {
System.out.println(this.iceAmericano.name);
return this.iceAmericano.price * quantity;
}
System.out.println(this.hotAmericano.name);
return this.hotAmericano.price * quantity;
}
public static void main(String[] args) {
Coffee ice = new Coffee("아이스아메리카노", 2500);
Coffee hot = new Coffee("따뜻한아메리카노", 2000);
CoffeeShop cs = new CoffeeShop(ice, hot);
// 아이스아메리카노 5잔 주문
int price = cs.orderCoffee(1, 5);
System.out.println(price);
}
}
DataClass와 record의 차이
has a 관계
클래스 내에 클래스가 포함된 관계를 Has A 관계라고 한다.
유틸리티 클래스