Expected Value

  • date 24th April, 2021 |
  • by Prwatech |
  • 0 Comments

Method Overriding in Scala

 

In scala we can redefine the same method to do different operations but with the same method name, this concept is called Method Overriding.

scala uses override modifier to override method from super class to sub class in the same code.

 In Scala, method overriding is achieved using the override keyword, which indicates that a method in a subclass is intended to override a method with the same signature in its superclass.

Scala also supports dynamic method dispatch, where the method implementation to be invoked is determined at runtime based on the actual type of the object. This enables polymorphic behavior, where different implementations of the same method can be execut depending on the runtime type of the object.

Understanding method overriding in Scala is fundamental for building flexible and modular object-oriented designs, enabling code reuse, and supporting polymorphism and subtype polymorphism concepts effectively within Scala applications.

use case 1:

scala> class Prwa(val name: String) {

     override def toString = getClass.getName + "[name=" + name + "]"

     }

scala> class Edu(codename: String) extends Prwa(codename) {

     override val name = "Edu"

     override val toString = "Edu"

     }

use case 2:

scala> class animal(val name: String) {

       override def toString = getClass.getName + "[name=" + name + "]"

     }

scala> class wild(codename: String) extends animal(codename) {

     override val name = "wild"

     override val toString = "wild"

     }

use case 3:

scala> class fruit(val name: String) {

       override def toString = getClass.getName + "[name=" + name + "]"

     }

scala> class Mango(codename: String) extends fruit(codename) {

     override val name = "Mango"

     override val toString = "Mango"

     }

Quick Support

image image