Consider two designs. (Basically one uses inheritance to reuse functionality fro
ID: 3677834 • Letter: C
Question
Consider two designs. (Basically one uses inheritance to reuse functionality from A and the other uses composition.)
************** Design 1 **************
public class A {
void f() {
. . .
}
}
public class B extends A {
public void f() {
super.f();
... new feature/behavior ...
}
}
************** Design 2 **************
public class A {
void f() {
. . .
}
}
public class B {
private A a;
public B(A a) {
this.a = a;
}
public void f() {
a.f();
... new feature/behavior ...
}
}
Which design has more coupling between A and B?
Design 1 has more coupling than design 2
Design 2 has more coupling than design 1
Both designs have the same coupling
It's impossible to tell without knowing the dynamic behavior
Design 1 has more coupling than design 2
Design 2 has more coupling than design 1
Both designs have the same coupling
It's impossible to tell without knowing the dynamic behavior
Explanation / Answer
Design 1 has more coupling than design 2
Inheritance is strongly coupled whereas composition is loosely coupled
Inheritance will bring you tight coupling, simply one change to base class can break many child classes.
Inheritance is compile time determined whereas composition is run-time
When compiled, your base class codes will be added to every child class.
Inheritance breaks encapsulation whereas composition does not
This is the reason why often composition is preferred to inheritance
Use inheritance only when all of the following criteria are satisfied (Coad's Rule):