Google News
logo
Scala - Interview Questions
What is Inheritance in Scala?
Inheritance in Scala is a mechanism that allows a class to inherit the properties (methods and fields) of another class. It enables code reuse and facilitates the creation of class hierarchies.

In Scala, inheritance is defined using the `extends` keyword. When a class extends another class, it inherits all the members (methods and fields) of the superclass. The subclass can then add or override these inherited members to customize its behavior.

Here's an example to illustrate inheritance in Scala :
class Animal {
  def eat(): Unit = {
    println("The animal is eating.")
  }
}

class Dog extends Animal {
  override def eat(): Unit = {
    println("The dog is eating.")
  }

  def bark(): Unit = {
    println("Woof!")
  }
}

val animal: Animal = new Animal()
animal.eat()  // Output: The animal is eating.

val dog: Dog = new Dog()
dog.eat()     // Output: The dog is eating.
dog.bark()    // Output: Woof!​
In this example, we have a base class `Animal` and a subclass `Dog` that extends `Animal`. The `Animal` class has a method `eat()` that prints a generic message. The `Dog` class overrides the `eat()` method to provide a more specific implementation for dogs and adds a new method `bark()`.

We create instances of both classes and invoke the `eat()` and `bark()` methods. When we invoke `eat()` on the `Animal` instance, it uses the implementation from the `Animal` class. However, when we invoke `eat()` on the `Dog` instance, it uses the overridden implementation from the `Dog` class.

Inheritance allows subclasses to reuse and extend the behavior of the superclass. It promotes code reuse, modularity, and the organization of classes into hierarchies based on their common characteristics. It also enables polymorphism, where an instance of a subclass can be treated as an instance of its superclass.

In Scala, multiple inheritance is not supported for classes, but it can be achieved through the use of traits, which are similar to interfaces in other languages. Traits allow a class to inherit multiple behaviors from different sources.

Overall, inheritance is a fundamental feature in object-oriented programming, and Scala provides a flexible and powerful mechanism to define class hierarchies and inherit and customize behavior.
Advertisement