Scala program to demonstrate the final method

Here, we are going to demonstrate the final method in Scala programming language.
Submitted by Nidhi, on July 07, 2021 [Last updated : March 11, 2023]

Scala – Final Method Example

Here, we will demonstrate the use of the final method. If we created a final method in a class then it cannot be overridden in the derived class. To create the final method, we need to use the final keyword.

Scala code to demonstrate the example of final method

The source code to demonstrate the final method is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to demonstrate the final method

class Demo1 {
  final def sayHi() {
    println("Hiii from Demo1");
  }

  def sayHello() {
    println("Hello from Demo1");
  }
}

class Demo2 extends Demo1 {
  /*A final method cannot be ovverid
	override def sayHi()
	{
		println("Hiii from Demo2");
	}
   */

  override def sayHello() {
    println("Hello from Demo2");
  }
}

object Sample {
  def main(args: Array[String]) {
    var obj = new Demo2();

    obj.sayHi();
    obj.sayHello();

  }
}

Output

Hiii from Demo1
Hello from Demo2

Explanation

Here, we used an object-oriented approach to create the program. And, we created an object Sample.

Here, we created two classes Demo1 and Demo2. The Demo1 class contains two methods sayHi() and sayHello(). The sayHi() is the final type. Then it cannot be overridden in any derived class. Then we override the sayHello() method in the Demo2 class.

In the main() function, we created the object of the Demo2 class and called sayHi() and sayHello() method.

Scala Final Variables, Methods & Classes Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.