TIL_230614

yesrin·2023년 6월 14일

TIL

목록 보기
6/15

Spring 입문 2주 차 과정 중 의문점 해결 기록

public class Consumer {

    void eat(Food food) {
        food.eat();
    }

    public static void main(String[] args) {
        Consumer consumer = new Consumer();
        consumer.eat(new Chicken());
        consumer.eat(new Pizza());
    }
}

interface Food {
    void eat();
}

class Chicken implements Food{
    @Override
    public void eat() {
        System.out.println("치킨을 먹는다.");
    }
}

class Pizza implements Food{
    @Override
    public void eat() {
        System.out.println("피자를 먹는다.");
    }
}

어떤 문제가 있었는지

Food food 와 consumer.eat(new Chicken()) 부분에 new Chiken이 들어가는 게 이해가 가질 않았다.

새롭게 알게 된 점

  1. 한번 생성하고 말 객체이기 때문에(지속적으로 사용하지 않기 때문에) new Chicken 등으로 줄여 사용할 수 있다.
  2. Food food는 Food interface를 implements 하고 있는 클래스들을 매개변수로 사용할 수 있다.

Food
를 implements 하고 있는 클래스들을 모두 매개변수로 사용할 수 있다.

profile
안녕하세요! 틀린 정보는 댓글 달아 주세요.

0개의 댓글