(Java programming) 데이터클래스 / 유틸리티 클래스

soosoorim·2024년 2월 19일
0

데이터클래스

멤버변수만 존재하는 클래스
기능(인스턴트 메소드)이 없는 클래스

  • 책, 커피, 음식 등
  • 속성은 있지만 기능이 없는 것도 클래스의 한 종류
  • 이런것들을 Data Class라고 부르며 VO(Value Object)클래스로도 부름

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 관계라고 한다.

  • CoffeeShop has a Coffee

유틸리티 클래스

0개의 댓글

관련 채용 정보