Composition and inheritance
In programming terms, to inherit or extend our classes we use the extends
or with
keywords. These are essential for the relationship between two or more classes or similar constructs. This association or relation between two classes or similar constructs can be in the form of inheritance (Is-A) or composition (Has-A). They are two different notions but they converge to some extent. In simple words, inheritance is a superclass-subclass relationship where the subclass inherits the implementation of the superclass, whereas composition is when a class depends on another object to provide some or all functionality. With an inheritance relationship, you can use the subclass object wherever superclass is expected. Think of it as this relationship between a Dictionary
and a Book
class:
class Book(val title: String) class Dictionary(name: String) extends Book(name) { // data and behavior }
We can picture the Book and Dictionary relationship as shown in the following...