Describe the process of 'Method Overriding' in Scala.

Instruction: Explain how method overriding is achieved in Scala and provide an example to illustrate.

Context: This question aims to evaluate the candidate's understanding of polymorphism in Scala, specifically the ability to override superclass methods in subclasses, including the use of the 'override' keyword.

Updated

Method overriding supplies a subclass implementation of an inherited method. A call through a superclass reference uses the implementation of the actual object. The overriding signature must conform to the inherited declaration; a reference return type can be narrowed to a subtype.

class Vehicle {
  def sound: String = "engine"
  def replacement(): Vehicle = new Vehicle
}
class ElectricCar extends Vehicle {
  override def sound: String = "quiet"
  override def replacement(): ElectricCar = new ElectricCar
}
trait Named { def name: String }
class NamedCar extends ElectricCar with Named {
  def name: String = "city car"
}
@main def overridingExample(): Unit = {
  val vehicle: Vehicle = new ElectricCar
  assert(vehicle.sound == "quiet")
  val car: ElectricCar = new ElectricCar().replacement()
  assert(car.sound == "quiet")
  assert(new NamedCar().name == "city car")
}

override is required when replacing a concrete inherited method. Implementing an abstract method, such as Named.name, does not require it, although it can help state intent. A final method cannot be overridden. An override may call super.method when the inherited implementation should participate. Inheritance and overriding

Changing parameter types can create an overload instead of an override; overload selection and dynamic dispatch are separate mechanisms. Preserve the parent API's behavioral contract, including error behavior and invariants. A conforming signature alone does not establish that a subclass is a valid behavioral substitute.

Related Questions