민서네집

상속 대신 Composition 으로 다른 객체의 기능 사용하는 예제 본문

Java

상속 대신 Composition 으로 다른 객체의 기능 사용하는 예제

브라이언7 2015. 1. 7. 16:10

너무 간단한 예제라 창피하지만...



package inheritance;

public class Rectangle {

	int width = 20;

	int height = 30;

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public int getArea() {
		return width * height;
	}

}


package inheritance;

public class Square {

	int width = 10;

	Rectangle rect;

	// Square 가 Rectangle 를 상속받지 않고도 Rectangle의 logic을 사용할 수 있음.
	// 상속 대신 Delegation, Composition 사용.

	public int getArea() {
		rect.setWidth(10);
		return rect.getArea();
	}
}


Comments