포함(composite)은 상속처럼 클래스를 재사용할 수 있는 방법이다. 다른 클래스 타입의 변수를 클래스의 멤버로 선언하는 것을 의미한다.
public class Employee {
int id;
String name;
Address address;
// Address 클래스타입의 address참조변수가 Employee멤버로 선언됨
}
class Address {
String city, country;
public Address(String city, String country) {
this.city = city;
this.country = country;
}
}
객체지향 프로그래밍에서 상속보다 포함관계를 사용하는 경우가 더 많다.
클래스 간의 관계를 설정할 때 상속으로 맺어줄지 포함으로 맺어줄지 어떤 기준으로 판별할 수 있을까?
(IS-A) ~은 ~이다 -> 상속관계
(Has-A) ~은 ~을 가지고있다 -> 포함관계