// 동물은 울음소리를 낸다.
public interface Animal {
void cry();
}
우리는 동물들이 울 수 있다는 공통적인 특성을 가지고 있음을 알고 있습니다.
이제 개와 고양이 두가지 동물 클래스로 인터페이스를 구현합니다.
// 개
public class Dog implements Animal {
@Override
public void cry() {
System.out.println("멍멍!");
}
}
// 고양이
public class Cat implements Animal {
@Override
public void cry() {
System.out.println("야옹!");
}
}
각각 개와 고양이를 선언하고, 각자의 울음소리를 기입합니다.
public class Person {
private Animal animal;
// 의존성 주입
public Person(Animal animal) {
this.animal = animal;
}
public void makeAnimalCry() {
animal.cry();
}
}
이제 Person 클래스를 만듭니다.
이때 Person은 어떤 동물과 함께할지 결정할 수 있습니다.
※ Animal 인터페이스는 Dog도 되고 Cat이 될 수도 있습니다.
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
Person personWithDog = new Person(myDog);
personWithDog.makeAnimalCry(); // 멍멍!
Animal myCat = new Cat();
Person personWithCat = new Person(myCat);
personWithCat.makeAnimalCry(); // 야옹!
}
}
Person 클래스는 Animal 인터페이스에 의존하고 있습니다.
이는 Person이 Dog나 Cat과 같은
구체적인 동물 클래스에 직접 의존하지 않는다는 것을 의미합니다.
Person 객체를 생성할 때,
생성자를 통해 어떤 동물과 함께할지를 결정합니다. 이것이 바로 의존성 주입입니다.
이렇게 인터페이스를 사용하면,
나중에 새로운 동물 클래스(예: Tiger, Lion 등)를 추가하더라도 Person 클래스를 수정할 필요가 없습니다.
단순히 새로운 동물 클래스를 Animal 인터페이스에 맞게 구현하기만 하면 됩니다.
결론 : 해당코드의 Person객체는 Animal객체에 의존한다.