Scala Tutorial

Basics

Control Statements

OOP Concepts

Parameterized - Type

Exceptions

Scala Annotation

Methods

String

Scala Packages

Scala Trait

Collections

Scala Options

Miscellaneous Topics

Extending a Class in Scala

In Scala, you can extend a class to create a subclass, which inherits the members of the superclass. This is a fundamental concept in object-oriented programming.

Here's how to extend a class in Scala:

1. Defining a Base Class:

First, let's define a simple class:

class Animal {
  def speak(): Unit = {
    println("Some sound")
  }
}

This Animal class has a method named speak that prints "Some sound".

2. Extending the Base Class:

To extend the Animal class, you use the extends keyword:

class Dog extends Animal {
  override def speak(): Unit = {
    println("Woof!")
  }
}

The Dog class is now a subclass of Animal. We've also overridden the speak method to provide a new implementation specific to Dog.

3. Using the Subclass:

Once you've defined your subclass, you can create instances of it and use its methods:

val myDog = new Dog()
myDog.speak()  // Prints: Woof!

4. Using super:

In the subclass, you can use the super keyword to refer to the superclass's members:

class Cat extends Animal {
  override def speak(): Unit = {
    super.speak()
    println("Meow!")
  }
}

If you create an instance of Cat and call its speak method:

val myCat = new Cat()
myCat.speak()
// Outputs:
// Some sound
// Meow!

Additional Points:

  • Constructors: Subclasses can also call the superclass's constructor using the super keyword.

  • Final Classes and Methods: If you don't want a class to be extended, you can mark it as final. Similarly, if you don't want a method to be overridden in subclasses, you can mark that method as final.

  • Abstract Classes: In Scala, you can also have abstract classes which cannot be instantiated directly but can be extended. Abstract classes can contain abstract members (without implementations).

  • Traits: In addition to class inheritance, Scala also supports trait mixin, allowing for a form of multiple inheritance. Traits are a powerful way to compose behaviors.

Inheritance in Scala works very much like in other object-oriented languages but offers more flexibility and power, especially when combined with traits.

  1. Inheritance in Scala:

    • Description: Inheritance allows a class to inherit properties and behaviors from another class. The base class is called the superclass, and the inheriting class is called the subclass.
    • Code Example (Base Class):
      class Animal(val name: String) {
        def speak(): Unit = println(s"$name makes a sound")
      }
      
    • Code Example (Subclass):
      class Dog(name: String, val breed: String) extends Animal(name) {
        override def speak(): Unit = println(s"$name barks loudly")
      }
      
  2. Creating subclasses in Scala:

    • Description: Subclasses are created by extending a base class using the extends keyword.
    • Code Example:
      class Cat(name: String, val color: String) extends Animal(name) {
        override def speak(): Unit = println(s"$name meows softly")
      }
      
  3. Scala extends keyword usage:

    • Description: The extends keyword is used to indicate that a class is inheriting from another class.
    • Code Example:
      class Bird(name: String, val species: String) extends Animal(name) {
        override def speak(): Unit = println(s"$name chirps loudly")
      }
      
  4. Overriding methods in extended classes:

    • Description: Subclasses can override methods of the superclass using the override keyword.
    • Code Example:
      class Horse(name: String, val color: String) extends Animal(name) {
        override def speak(): Unit = println(s"$name neighs loudly")
      }
      
  5. Multiple inheritance in Scala:

    • Description: Scala supports multiple inheritance through traits, allowing a class to inherit from multiple sources.
    • Code Example:
      trait Swimmer {
        def swim(): Unit = println("Swimming")
      }
      
      class Dolphin(name: String) extends Animal(name) with Swimmer
      
  6. Using super keyword in Scala subclasses:

    • Description: The super keyword is used to refer to the superclass, allowing access to its methods and properties.
    • Code Example:
      class FlyingBird(name: String, val species: String) extends Bird(name, species) {
        def fly(): Unit = {
          super.speak()
          println(s"$name soars through the sky")
        }
      }
      
  7. Scala abstract classes and class extension:

    • Description: Abstract classes cannot be instantiated and may contain abstract methods. Subclasses must provide implementations for abstract methods.
    • Code Example (Abstract Class):
      abstract class Shape {
        def area(): Double
      }
      
    • Code Example (Subclass):
      class Circle(radius: Double) extends Shape {
        override def area(): Double = math.Pi * radius * radius
      }
      
  8. Polymorphism in Scala classes:

    • Description: Polymorphism allows objects of different classes to be treated as instances of a common base class.
    • Code Example:
      val dog: Animal = new Dog("Buddy", "Golden Retriever")
      val cat: Animal = new Cat("Whiskers", "Gray")
      val horse: Animal = new Horse("Spirit", "Brown")
      
      val animals: List[Animal] = List(dog, cat, horse)
      animals.foreach(animal => animal.speak())
      
  9. Mixins and traits in Scala:

    • Description: Traits provide a mechanism for mixin composition, allowing classes to inherit behaviors from multiple sources.
    • Code Example (Trait):
      trait Jumper {
        def jump(): Unit = println("Jumping")
      }
      
      class Kangaroo(name: String) extends Animal(name) with Jumper
      
  10. Initialization order in Scala subclasses:

    • Description: The order of initialization in subclasses involves initializing the superclass first, followed by the subclass.
    • Code Example:
      class Fish(name: String) extends Animal(name) with Swimmer {
        println(s"Fish class initialized for $name")
      }
      
  11. Scala sealed classes and class extension:

    • Description: Sealed classes restrict extension to classes defined in the same file, enabling exhaustive pattern matching.
    • Code Example (Sealed Class):
      sealed abstract class Vehicle
      case class Car(model: String) extends Vehicle
      case class Bike(brand: String) extends Vehicle
      
  12. Scala case classes and class extension:

    • Description: Case classes in Scala are often used for modeling data and provide convenient syntax for creating instances.
    • Code Example (Case Class):
      case class Point(x: Double, y: Double)
      val origin: Point = Point(0.0, 0.0)