Scala Field Overriding

In Scala, we can override the fields but with some rules. Let’s understand it with some examples.

If you look at the below code, where we are overriding the field named ‘age’ from 30 to 35. It will give the compile time error saying “Variable ‘age’ needs override modifier”.

Compile time error

As a solution, we must use either override keyword or override annotation while overriding any method or field of super class.Let’s see below the solution of above problem.

class Person {
  val age : Int =30

}


class employee extends Person{
  override val age:Int =35   //Override Keyword

  def display(){
    println(age)
  }
}

object emp{
  def main(args: Array[String]): Unit = {
    var e = new employee
    e.display()
  }
}
Output: 35

One important point to note here is that we can override only those variables which are declared by using val keyword, not by var keyword. If we use override keyword with var, it throws the error message as “variable age cannot override a mutable variable”

class Person {
  var age : Int =30
}

class employee extends Person{
  override var age:Int =35   //Override Keyword

  def display(){
    println(age)
  }
}

object emp{
  def main(args: Array[String]): Unit = {
    var e = new employee
    e.display()
  }
}
Output:
Error:(10, 16) overriding variable age in class Person of type Int;
 variable age cannot override a mutable variable
  override var age:Int =35   //Override Keyword
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...