[Java] 객체 컴포지션 이해 예시

myeonghyun·2022년 8월 23일
0

공부

목록 보기
3/5

CustomerRunner.java

package customer;

public class CustomerRunner {

	public static void main(String[] args) {
		
		Address homeAddress = new Address("line1", "Jeonju", "500035");
		Customer customer = new Customer("MyeongHyun", homeAddress);
		
		Address workAddress = new Address("line 1 for work", "Seoul", "500078");
		customer.setWorkAddress(workAddress);
		
		System.out.println(customer);
	}

}

Customer.java

package customer;

public class Customer {
	
	//state
	private String name;
	private Address homeAddress;
	private Address workAddress;
	
	//creating
	public Customer(String name, Address homeAddress) {
		this.name = name;
		this.homeAddress = homeAddress;
	}
	
	//operations
	public Address getHomeAddress() {
		return homeAddress;
	}

	public void setHomeAddress(Address homeAddress) {
		this.homeAddress = homeAddress;
	}

	public Address getWorkAddress() {
		return workAddress;
	}

	public void setWorkAddress(Address workAddress) {
		this.workAddress = workAddress;
	}
	
	public String toString() {
		return String.format("name - [%s] home address - [%s] work address - [%s])", name, homeAddress, workAddress);
	}
	
}

Address.java

package customer;

public class Address {
	private String line1;
	private String city;
	private String zip;
	
	public Address(String line1, String city, String zip) {
		super();
		this.line1 = line1;
		this.city = city;
		this.zip = zip;
	}
	
	public String toString() {
		return line1 + " " + city + " " + zip;
	}
}

profile
while(1)

0개의 댓글