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:

class Birthday extends GreetingCards {
//Birthday - Subclass or child class
//GreetingCards - Parent class
}

Let’s understand this with an example.

Parent Class:

class Bank {
    var InterestRate: Int = 8
  def bankInterest(): Unit ={
    println("This bank's interest rate is : " +InterestRate)
  }
}

Child class extends parent class.

class hdfcBank extends Bank{
  var hdfcInterestRate = 7.5
  bankInterest()    //calling method of parent class
  println("Hdfc bank interest rate is : "+ hdfcInterestRate)
}

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

object OurBank {
  def main(args: Array[String]): Unit = {
    new hdfcBank
  }
}
Output:
Global bank's interest rate is : 8
Hdfc bank interest rate is : 7.5

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.

package main.com.testingpool

class A {
  println("A")

}

class B extends A{
  println("B")

}
class C extends B{
  println("C")

}

object ABC{
  def main(args: Array[String]): Unit = {
    new C
  }
}
Output:
A
B
C

Example- Hierarchical Inheritance

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

package main.com.testingpool

class A {
  println("A")

}

class B extends A{
  println("B")

}
class C extends A{
  println("C")

}

object ABC{
  def main(args: Array[String]): Unit = {
    new B()
    println("****")
    new C()
  }
}
Output:
A
B
****
A
C
Avatar photo

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...