Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the responsive-lightbox domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the hueman domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114
Scala Field Overriding - Testingpool

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...