1. 롯데리아 앱 만들기
1-1. 기본 버거 만들기 (상태 - 생성자 - getter 는 세트)

상태를 만들었으면 당연히 세트처럼!!

생성자도 만들어줌. 초기화 해야하니까!

getter도 만들어줌!!!! 세트! 상태가 만들어지면 생성자와 getter는 객체지향에서 세트처럼 만들어줘야 한다.


name은 매개변수로 받아서 오면 되니까 name 으로 작성
1-2. 쉬림프 버거 만들기

디폴트 생성자가 없어서 오류! 당황하지 말게나

Burger 클래스한테 상속 받아서 쓰면 되니까 필드값은 material 만 추가하면 됨. alt + insert로 생성자를 만들면 자동으로! super까지 딱!

당연히 한 세트인 getter도 넣어준다.

LotteApp 클래스에 새우버거를 만들어줌. (ShrimpBurger는 Burger를 상속 받는다.) Burger b2 = new ShrimpBurger("새우버거", 2000, "새우"); 이미 Burger클래스에 출력문이 있으니, 상속받는 ShrimpBurger는 출력문이 필요없다.
1-3. 컴포지션 사용
잘 만들어진 클래스를 상속이 아닌 걸로 사용하고 싶다 > 필요한 클래스들을 ‘상태’로 가짐

BurgerSet에서 필요한 Burger와 Coke의 클래스를 상태 값으로 가진 것을 확인.

컴포지션 결합 코드!!! 버거세트가 버거랑 콜라 클래스를 다 가지는것! 만들어진 걸 버거세트한테 전달한다!!

//결과
1-4. 가격 출력
완성된 코드
package ex06.example7; public class LotteApp { public static void main(String[] args) { Burger b1 = new Burger("기본버거", 1000); //[Burger] Burger b2 = new ShrimpBurger("새우버거", 2000, "새우"); //[Burger, ShrimpBurger] Coke c1 = new Coke("콜라", 1000); System.out.println(); BurgerSet set = new BurgerSet(new Burger("기본버거", 1000), new Coke("콜라", 1000)); System.out.println(); System.out.println("총 가격은 : " + set.getTotalPrice()); // System.out.println(set.getBurger().getPrice()); // System.out.println(set.getCoke().getPrice()); } }
package ex06.example7; public class Burger { private String name; private int price; public Burger(String name, int price) { this.name = name; this.price = price; System.out.println(name+"가 만들어졌어요"); } public String getName() { return name; } public int getPrice() { return price; } }
package ex06.example7; public class ShrimpBurger extends Burger { private String material; //재료 public String getMaterial() { return material; } public ShrimpBurger(String name, int price, String material) { super(name, price); this.material = material; } }
package ex06.example7; public class Coke { private String name; private int price; public Coke(String name, int price) { this.name = name; this.price = price; System.out.println(name + "가 만들어졌습니다."); } public String getName() { return name; } public int getPrice() { return price; } }
package ex06.example7; //컴포지션 사용 public class BurgerSet { //has 관계. Burger와 Coke를 가짐 private Burger burger; private Coke coke; //필요한 애들을 상태로 가짐. //생성자로 초기화 할거라 빈값 public BurgerSet(Burger burger, Coke coke) { this.burger = burger; this.coke = coke; System.out.println("버거 세트가 만들어졌어요."); } public int getTotalPrice() { return burger.getPrice() + coke.getPrice(); } public Burger getBurger() { return burger; } public Coke getCoke() { return coke; } }
Share article