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 Final - Testingpool

Scala Final

In Scala, Final is a keyword that is used to prevent inheritance of super class in any of the child classes.We can declare variables, methods and classes with Final keyword. Let’s understand them with example one by one.

Scala Final variable:

In the below example, we have declared a final variable named as ‘age’. So, it can not be inherited in the child class ”employee”.It throws error message as ‘Variable age can not override final member’.

class Person {
  final 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: Variable age can not override final member.

Scala Final Method:

In the below example, the method named ‘display’ is a final method in parent class. So, this method can not be overridden in child class.

class Person {
final def display(): Unit ={
  print("Name of Person")
}
}

class employee extends Person{
  override def display(){
    println("Name of Employee")
  }
}

object emp{
  def main(args: Array[String]): Unit = {
    var e = new employee
    e.display()
  }
}
Output: Method 'display' can not override final member

Scala Final Class:

In the below example, Parent class is created as final class. It can not be extended by any other class.

final class Person {
  def display(): Unit ={
  print("Name of Person")
}
}

class employee extends Person{
  override def display(){
    println("Name of Employee")
  }
}

object emp{
  def main(args: Array[String]): Unit = {
    var e = new employee
    e.display()
  }
}
Output:
Error:(10, 24) illegal inheritance from final class Person
class employee extends Person{

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