DEV Community

Cover image for Inheritance vs Composition
Aaron
Aaron

Posted on

Inheritance vs Composition

Object-Oriented Programming (O.O.P.) has been relevant in the land of programming. For this article, the two most commonly used concepts will be discussed. This article provides surface-level knowledge between the two. Java will be the programming language used.

Composition

This is a concept with a has-a relationship between classes. The code below showcases this using the Java programming language.

class Caret {
  Caret() {}
}

class TextEditor {
  Caret caret;

  TextEditor() {
    caret = new Caret();
  }
}

class RichTextEditor {
  Caret caret;
  String color;  

  RichTextEditor(String color) {
    caret = new Caret();
    this.color = color;
  }
}
Enter fullscreen mode Exit fullscreen mode

The code above states that the class, TextEditor has a caret and a color. In other words, it is made up of the aforementioned fields.

The RichTextEditor has a caret and color. It does not depend on the TextEditor class, unlike in inheritance; which will be shown below.

Composition is like making food. The main class is the food and its ingredients are its fields/properties.

Inheritance

This is a concept with an is-a relationship between classes and is only limited to being one-to-one. The code below showcases this using the Java programming language.

class Caret {
  public Caret() {}
}

class TextEditor {
  Caret caret;

  TextEditor() {
    caret = new Caret();
  }
}

class RichTextEditor extends TextEditor {
  String color;  

  RichTextEditor(String color) {
    super();
    this.color = color;
  }
}
Enter fullscreen mode Exit fullscreen mode

The code above states that the RichTextEditor class inherits from the TextEditor class. Everything that in TextEditor becomes a part of RichTextEditor.

Now, for our food analogy, let's say that Jollibee spaghetti inherits from spaghetti. If we change spaghetti to be a carbonara, for whatever reason, then our Jollibee spaghetti would then become a Jollibee carbonara without us touching it!

Conclusion

That's it! Thank you for reading. May you have a wonderful day. Happy coding. God bless! :)

Top comments (0)