クラスを関連付ける 2 つの基本的な方法はinheritance
、 とcomposition
です。2 つのクラス間に継承関係を確立すると、 と を利用でき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();
}
}
ただし、将来のある時点で Peel() の戻り値を type に変更したい場合はPeel
、Example1 が Apple を直接使用し、Fruit について明示的に言及していなくても、Example1 コードのコードを壊すことになります。
Composition
Apple が Fruit の の実装を再利用するための代替方法を提供しますpeel()
。Fruit を拡張する代わりに、Apple はインスタンスへの参照を保持し、単に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
。