Inheritance in Scala

Inheritance is a fundamental concept in object-oriented programming, and Scala supports inheritance just like other object-oriented languages. In Scala, you can create a subclass that inherits from a superclass and extends its behavior. Here's a brief overview of inheritance in Scala:

1. Defining a superclass: To define a superclass in Scala, use the "class" keyword followed by the class name and its fields and methods. Here's an example:

   
``
   class Animal(name: String) {
       def walk(): Unit = {
           println(s"$name is walking")
       }
   }
   

In this example, “Animal” is a superclass that has a single field (“name”) and a method (“walk”).

2. Defining a subclass: To define a subclass in Scala, use the “extends” keyword followed by the superclass name. Here’s an example:


class Dog(name: String) extends Animal(name) {
def bark(): Unit = {
println(s”$name is barking”)
}
}
val dog = new Dog(“Rex”)
dog.walk() // prints “Rex is walking”
dog.bark() // prints “Rex is barking”


`

In this example, “Dog” is a subclass of “Animal” that has a single method (“bark”). The constructor for “Dog” takes a single argument, which is passed to the constructor of “Animal”using the “name” parameter. The “Dog” class inherits the “walk” method from its superclass.

3. Overriding methods: In Scala, you can override methods from a superclass in a subclass. Here’s an example:


`
class Cat(name: String) extends Animal(name) {
override def walk(): Unit = {
println(s”$name is walking like a cat”)
}
}
val cat = new Cat(“Whiskers”)
cat.walk() // prints “Whiskers is walking like a cat”


`

In this example, “Cat” is a subclass of “Animal” that overrides the “walk” method. When the “walk” method is called on an instance of “Cat”, the overridden method is executed instead of the method in the superclass.

Overall, inheritance in Scala provides a powerful and flexible way to extend classes and create new behavior. You can define a superclass with fields and methods, and then create subclasses that inherit and extend that behavior. You can also override methods in a subclass to modify or replace the behavior of the superclass.