Scala – Inheritance

In the previous post, we have learnt about method overloading. Now, we will see what is Inheritance in scala.

Inheritance is used for reusability of the code. When a class wants to use/reimplement code from another class, then that class has to use keyword extends to inherit properties from another class. The class which is extended , is called the Parent class or Super class. The class which extends another class, is called the subclass or child class.

Syntax:

Let’s understand this with an example.

Parent Class:

Child class extends parent class.

Now, create an object of child class and execute the program. Child class is directly calling parent class method.

Types of Inheritance in Scala

Scala supports various types of inheritance including single, multilevel, multiple, hierarchal and hybrid.A point to be noted here is that , a class can only use single, multilevel and hierarchal inheritance. Multiple and hybrid will be used by Traits, which we will study in coming chapters.

Multilevel Inheritance in scala:

Let’s understand with an example where class C extends class B and class B extends class A.

Example- Hierarchical Inheritance

In this example, class B and C both extends class A.

Scala - Method Overriding
Scala - This Keyword
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *