Inheritance
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in Scala by which one class is allowed to inherit the features(fields and methods) of another class.
Important terminology:
- Super Class: The class whose features are inherited is known as superclass(or a base class or a parent class).
- Sub Class: The class that inherits the other class is known as a subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
- Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
The keyword used for inheritance is extends.
Syntax:
class parent_class_name extends child_class_name{ // Methods and fields } |
Type of inheritance
Below are the different types of inheritance which are supported by Scala.
Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to another class. In the below image, class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C.
Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below image, class A serves as a base class for the derived classes B, C, and D.
Multiple Inheritance: In Multiple inheritance, one class can have more than one superclass and inherit features from all parent classes. Scala does not support multiple inheritance with classes, but it can be achieved by traits.
Hybrid Inheritance: It is a mix of two or more of the above types of inheritance. Since Scala doesn’t support multiple inheritance with classes, hybrid inheritance is also not possible with classes. In Scala, we can achieve hybrid inheritance only through traits.
0 Comments