The Short Answer
It's really not as black and white as that. In short, yes. Any situation that can be solved with inheritance can be solved, near enough, by composition. So in short, the answer to your question is yes; inheritance can be replaced by composition.
Why it's not that simple
When to use Inheritance
It's not a matter of whether you CAN swap them out. It depends on the context that you're programming in, and it becomes more of a question of whether you SHOULD swap them out. Take this simple example in Java:
public class Person
{
// Assume every person can speak.
public void speak()
{
}
}
Now, let's say we have another class, Dave. Dave IS a person.
public class Dave extends Person
{
public void speak() { System.out.println("Hello!"); }
public void killSomeone() {} // Dave is a violent Guy.
}
Now would it make more sense for the class Dave
to look like this?
public class Dave
{
private Person p;
// Composition variant.
public void speak() { p.speak(); }
public void killSomeone() {} // Dave is a violent Guy.
}
This code implies Dave has a person. It's not as simple and doesn't explain itself as well. Also, anything a Person can do, Dave can do, so it makes sense that we assert Dave is a "Person".
When to use Composition
We use Composition when we only want to expose part of the class' interface. Following our previous example, let's say Dave
has a Guitar
. The guitar has a more complex interface:
public class Guitar
{
public Color color;
// Guitar's color.
public Tuning tuning;
// Guitar's tuning.
public void tuneGuitar()
{}
public void playChord()
{}
public void setColor()
{}
}
Now, if we were to inherit this class, what would the outcome be?
Well, class Dave would now have attributes color
and tuning
. Does Dave
have a tuning? I think not! This is where inheritance makes no sense. We don't want to expose the entire Guitar
interface along with the Dave
interface. We only want the user to be able to access what Dave
needs to access, so in this case we would use some composition:
public class Dave extends Person
{
private Guitar guitar;
// Hide the guitar object. Then limit what the user can do with it.
public void changeGuitarColor(Color newColor)
{
// So this code makes a lot more sense than if we had used inheritance.
guitar.setColor(newColor);
}
public void speak() { System.out.println("Hello!"); }
public void killSomeone() {} // Dave is a violent Guy.
}
Conclusion
It's really not a case of what can replace the other. It's about the situation that you are implementing the techniques in. Hopefully, by the end of the example you'll see that inheritance is for situations where one object IS A
object, and composition is used when one object HAS A
object.