Class inheritance
You already know that inheritance plays an important role in good object-oriented design. We are lucky enough to have constructs such as classes with names, and we can increase the possibility of relating those with other classes by using inheritance. Inheritance is about forming a meaningful hierarchy of classes to solve the purpose of code reuse. And mark my words, I mentioned meaningful hierarchies. I'll justify my words later. Let's take a look at how we can extend classes to make a hierarchy.
Extending classes
We use the extend
keyword to inherit a class. Let's see our Book
example to understand this:
class Book(val title: String){ // data and behaviour for Book } class Dictionary(name: String) extends Book(name) { // data and behaviour for dictionary } object BookApp extends App { val dictionary = new Dictionary("Collins") println(dictionary.title) }
The result is as follows:
Collins
We can see that Dictionary
inherits from Book
or Dictionary
and...