Scala Tutorial

Basics

Control Statements

OOP Concepts

Parameterized - Type

Exceptions

Scala Annotation

Methods

String

Scala Packages

Scala Trait

Collections

Scala Options

Miscellaneous Topics

Method Overriding in Scala

Method overriding is a feature in Scala (as well as other object-oriented languages) that allows a subclass to provide a specific implementation of a method that's already defined in its superclass or one of its superclasses. The overridden method in the subclass should have the same name, return type, and parameters as the method in the superclass.

Let's delve into method overriding in Scala:

Basic Example:

class Animal {
  def sound(): String = {
    "Some sound"
  }
}

class Dog extends Animal {
  override def sound(): String = {
    "Woof"
  }
}

val dog = new Dog()
println(dog.sound())  // Output: Woof

In this example, the Dog class overrides the sound method of the Animal class.

Points to remember about method overriding:

  • Using the override Keyword: In Scala, you must use the override keyword when you override a method. This helps catch errors in case you unintentionally try to override a method that doesn't exist in a parent class.

  • Cannot Override a final Method: If a method is declared as final in the superclass, it cannot be overridden in any subclass.

  • Same Method Signature: The overriding method must have the same name, return type (or subtype), and same parameter list as the method of the parent class.

  • Super Keyword: You can use the super keyword to refer to the overridden method or other members of the superclass.

class Cat extends Animal {
  override def sound(): String = {
    super.sound() + "... but usually Meow"
  }
}

val cat = new Cat()
println(cat.sound())  // Output: Some sound... but usually Meow
  • Constructor Parameters and Overriding: In Scala, you can override methods that have parameters, including those parameters coming from class constructors.
class Shape(val name: String) {
  def description: String = s"I am a shape named $name."
}

class Circle(override val name: String, val radius: Double) extends Shape(name) {
  override def description: String = super.description + s" I am specifically a circle with a radius of $radius."
}

val circle = new Circle("MyCircle", 5.0)
println(circle.description)
  • Overriding a Variable: In Scala, you can override a val or a var with another val, but there are some rules and considerations to keep in mind. Typically, overriding fields is less common and can lead to more complex and hard-to-read code, so use it judiciously.

  • Overriding Type Members: In addition to methods and fields, Scala allows for the overriding of type members.

Conclusion:

Method overriding in Scala enables subclasses to provide specific implementations for methods already defined in a superclass, allowing for polymorphism. It's essential to be familiar with the rules and semantics of overriding to avoid common pitfalls and to produce clear, maintainable code.

  1. How to override methods in Scala:

    • Description: Method overriding in Scala involves providing a new implementation for a method in a subclass or trait, replacing the implementation in the superclass or parent trait.
    • Code Example:
      class Animal {
        def makeSound(): String = "Generic animal sound"
      }
      
      class Cat extends Animal {
        override def makeSound(): String = "Meow!"
      }
      
      val cat = new Cat()
      val sound = cat.makeSound() // "Meow!"
      
  2. Scala abstract classes and method overriding:

    • Description: Abstract classes in Scala can declare abstract methods that must be implemented by concrete subclasses using the override keyword.
    • Code Example:
      abstract class Shape {
        def area(): Double
      }
      
      class Circle(radius: Double) extends Shape {
        override def area(): Double = math.Pi * radius * radius
      }
      
  3. Using the 'override' keyword in Scala:

    • Description: The override keyword is used to explicitly indicate that a method in a subclass or trait is intended to override a method in a superclass or parent trait.
    • Code Example:
      class Dog extends Animal {
        override def makeSound(): String = "Woof!"
      }
      
  4. Scala traits and method overriding:

    • Description: Traits in Scala can also declare methods that can be overridden by classes or other traits that extend them.
    • Code Example:
      trait Speaker {
        def speak(): String
      }
      
      class Person extends Speaker {
        override def speak(): String = "Hello, World!"
      }
      
  5. Dynamic method dispatch in Scala:

    • Description: Dynamic method dispatch refers to the runtime determination of the method to be invoked based on the actual type of the object.
    • Code Example:
      val animal: Animal = new Cat()
      val dynamicSound = animal.makeSound() // Resolves to "Meow!" at runtime
      
  6. Super keyword in Scala method overriding:

    • Description: The super keyword is used to invoke the overridden method from the superclass or parent trait within the overriding method.
    • Code Example:
      class Subclass extends Superclass {
        override def overriddenMethod(): String = {
          val resultFromSuper = super.overriddenMethod()
          s"Modified result: $resultFromSuper"
        }
      }
      
  7. Preventing method override in Scala:

    • Description: Methods can be marked as final in Scala, preventing them from being overridden in subclasses or traits.
    • Code Example:
      class NonOverridable {
        final def cannotOverride(): String = "This cannot be overridden"
      }