두 가지 기본적인 방법은 두 클래스 사이의 상속 관계를 구축 .When inheritance
및 composition
, 당신은 dynamic binding
및 polymorphism
을 활용할 수 있습니다.
inheritance
관계로 인해 수퍼 클래스의 interface
을 변경하는 것이 어려워지면 composition
에서 제공하는 대체 방법을 살펴 보는 것이 좋습니다. 목표가 코드 재사용 인 경우 composition
은 변경하기 쉬운 코드를 산출하는 접근 방식을 제공합니다. 미래의 어떤 시점에서, 그러나, 당신은 껍질의 반환 값을 변경하려면
class Fruit {
// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {
System.out.println("Peeling is appealing.");
return 1;
}
}
class Apple extends Fruit {
}
class Example1 {
public static void main(String[] args) {
Apple apple = new Apple();
int pieces = apple.peel();
}
}
() 예 1 직접 애플을 사용하여 명시 적으로 언급하지 비록 당신은 예 1 코드에 대한 코드를 깰 것, Peel
를 입력합니다 과일.
Composition
은 사과가 peel()
이라는 과일의 구현을 재사용 할 수있는 대체 방법을 제공합니다. Apple은 Fruit을 확장하는 대신 Fruit
인스턴스에 대한 참조를 보유하고 Fruit에서 peel()
을 호출하는 자체 peel()
메서드를 정의 할 수 있습니다. 여기 코드는 다음과 같습니다
class Fruit {
// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {
System.out.println("Peeling is appealing.");
return 1;
}
}
class Apple {
private Fruit fruit = new Fruit();
public int peel() {
return fruit.peel();
}
}
class Example2 {
public static void main(String[] args) {
Apple apple = new Apple();
int pieces = apple.peel();
}
}
Inheritance
당신에게 Composition
보다 높은 커플 링을 제공합니다.
"전체적인 커플 링"이란 무엇입니까? 일반적으로 거의 모든 종류의 커플 링은 바람직하지 않습니다. –
몇 가지 예를 들려주세요. – Nick
예 : – mezamorphic