🔌 SPARTA/Courses

걷기반 3회차: 생성자, this, Order

eunjiom 2026. 1. 21. 21:01

1. 생성자의 역할

  • 생성자 적용 시 객체 생성과 동시에 필수 값 입력 > 완전한 상태
  • 생성자 적용 X
Menu menu = new Menu();
menu.name = "아메리카노";
menu.price = 3000;
menu.stock = 10;
  • 생성자 적용
Menu(String name, int price, int stock) {
    this.name = name;
    this.price = price;
    this.stock = stock;
    this.soldOut = stock == 0;
}

Menu menu = new Menu("아메리카노", 3000, 10);

 

2. this 

1) this 의미

  • 해당 객체 자신
  • 필드와 파라미터 이름이 같을 때 구분하기 위해 사용
  • this = 객체의 필드 / name = 생성자의 파라미터
  • this X
Menu(String name, int price) {
    name = name;
    price = price;
}
  • this O
Menu(String name, int price) {
    this.name = name;
    this.price = price;
}

 

2) 메서드에서 this 사용

class Menu {
    int price;

    void changePrice(int price) {
        price += 100;
    }
}
  • 단순 가독성이 아닌 객체 필드(객체 상태)를 변경하기 위해 사용
  • (이름이 같을 경우) this가 없을 때 파라미터만 변경됨
  • 객체 필드임을 지정
void changePrice(int price) {
    this.price += price;
}

 

3. 기존 Menu 구조 문제점

selectedMenu.sell(quantity);
  • 메뉴가 스스로 주문을 처리
  • 주문 취소 / 상태 변경 시 Menu가 계속 커짐 = 책임이 과도하게 몰림
  • 책임 분리 필요 > Order 클래스 도입

4. Menu 클래스

  • 역할: 메뉴 정보 관리 / 재고 상태 관리 / "팔 수 있는지" 판단
class Menu {

    String name;      // 메뉴 이름 (아메리카노, 라떼 등)
    int price;        // 메뉴 가격
    int stock;        // 재고 수량
    boolean soldOut;  // 품절 여부 (true = 품절)

    // 생성자
    // 메뉴 객체가 만들어질 때 필수 정보들을 한 번에 초기화
    Menu(String name, int price, int stock) {
        this.name = name;           // 객체 필드 name에 전달받은 name 저장
        this.price = price;         // 객체 필드 price에 전달받은 price 저장
        this.stock = stock;         // 객체 필드 stock에 전달받은 stock 저장

        // 재고가 0이면 품절 상태로 시작
        // stock 값에 따라 soldOut 상태를 자동으로 결정
        this.soldOut = stock == 0;
    }

    // 메뉴 정보를 출력하는 메서드
    // 메뉴의 현재 상태를 보여주는 역할
    void printInfo() {

        // 품절 상태라면
        if (this.soldOut) {
            System.out.println(this.name + " : SOLD OUT");
        } 
        // 판매 가능 상태라면
        else {
            System.out.println(
                this.name + " : " 
                + this.price + "원 (" 
                + this.stock + "개 남음)"
            );
        }
    }

    // 해당 수량만큼 판매 가능한지 판단하는 메서드
    // 실제로 판매하지는 않고, 가능 여부만 true/false로 반환
    boolean canSell(int quantity) {

        // 품절이 아니고 && 재고가 주문 수량 이상이면 판매 가능
        return !this.soldOut && this.stock >= quantity;
    }

    // 재고를 줄이는 메서드
    // 실제 주문이 확정된 후에 호출됨
    void decreaseStock(int quantity) {

        // 재고 감소
        this.stock -= quantity;

        // 재고가 0이 되면 품절 상태로 변경
        if (this.stock == 0) {
            this.soldOut = true;
        }
    }
}

 

5. Order 클래스

  • 역할: 어떤 메뉴를 / 몇 개 주문했는지 / 주문 가능 여부 판단 / 주문처리
class Order {

    Menu menu;     // 주문한 메뉴
    int quantity;  // 주문 수량

    // 주문 객체 생성 시 어떤 메뉴를 몇 개 주문했는지 저장
    Order(Menu menu, int quantity) {
        this.menu = menu;         // 주문 대상 메뉴
        this.quantity = quantity; // 주문 수량
    }

    // 주문을 실제로 처리하는 메서드
    void process() {

        // 메뉴에서 판매 가능 여부만 확인
        if (!menu.canSell(quantity)) {
            System.out.println("주문 불가: 재고 부족 또는 품절");
            return;
        }

        // 판매 가능하면 메뉴의 재고를 감소
        menu.decreaseStock(quantity);

        // 주문 완료 메시지 출력
        System.out.println(
            menu.name + " " + quantity + "개 주문 완료!"
        );
    }
}

 

6. Main 클래스 전체 흐름

import java.util.*;

public class Main {
    public static void main(String[] args) {

        // 여러 메뉴를 관리하기 위한 리스트
        List<Menu> menus = new ArrayList<>();

        // 메뉴 객체 생성 및 추가
        menus.add(new Menu("아메리카노", 3000, 10));
        menus.add(new Menu("라떼", 3500, 5));
        menus.add(new Menu("쥬스", 5000, 12));

        // 현재 메뉴 상태 출력
        for (Menu menu : menus) {
            menu.printInfo();
        }

        Scanner sc = new Scanner(System.in);

        // 사용자 입력
        System.out.println("주문할 메뉴 이름을 입력하세요:");
        String name = sc.nextLine();

        System.out.println("수량을 입력하세요:");
        int quantity = sc.nextInt();

        // 입력한 이름과 같은 메뉴 찾기
        Menu selected = null;
        for (Menu menu : menus) {
            if (menu.name.equals(name)) {
                selected = menu;
                break;
            }
        }

        // 메뉴를 찾지 못했을 경우
        if (selected == null) {
            System.out.println("존재하지 않는 메뉴입니다.");
            return;
        }

        // 주문 객체 생성
        Order order = new Order(selected, quantity);

        // 주문 처리
        order.process();

        // 주문 후 메뉴 상태 출력
        System.out.println("\n주문 후 메뉴 상태");
        for (Menu menu : menus) {
            menu.printInfo();
        }
    }
}

 

7. 구조변화

  • 기존
Menu
 ├─ 정보
 ├─ 출력
 └─sell()  ← 책임 과다
  • 변경
Menu  → 상태 관리
Order → 주문 처리
Main  → 흐름 제어

 

'🔌 SPARTA > Courses' 카테고리의 다른 글

알고리즘 개념  (1) 2026.01.27
걷기반 4회차: 상속과 제네릭, enum  (1) 2026.01.23
걷기반 2회차: 배열(Array와 List)  (0) 2026.01.16
자바 개념 확장  (0) 2026.01.15
객체지향 특징  (0) 2026.01.14