Scala program to extend a trait in a class without implementing the abstract method

Here, we are going to learn how to extend a trait in a class without implementing the abstract method in Scala programming language?
Submitted by Nidhi, on June 05, 2021 [Last updated : March 12, 2023]

Scala - Extending a Trait in a Class

Here, we will create a simple trait with an abstract method but we will not implement the method of the trait in the class. Then we need to extend traits in abstract class only and we know that we cannot create the object of the abstract class.

Scala code to extend a trait in a class without implementing the abstract method

The source code to extend a trait in a class without implementing the abstract method is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to extends a trait in a class
// without implementing abstract method

trait SampleTrait {
  def sayHello();
}

abstract class Test extends SampleTrait {
  def sayHi() {
    println("Hi from Test class");
  }
}

object Sample {
  def main(args: Array[String]) {
    // Abstract class cannot be instantiated.
    // var obj = new Test();

    println("Hello from Main() message");
  }
}

Output

Hello from Main() message

Explanation

In the above program, we used an object-oriented approach to create the program. Here, we created a trait SampleTrait that contains an abstract method sayHello(). Then we extend the SampleTrait into the abstract class Test.

Then we created a singleton object Sample and defined the main() function. The main() function is the entry point for the program.

In the main() function, we cannot create the object of the Test class. Then we printed the "Hello from Main() message" on the console screen.

Scala Trait Programs »





Comments and Discussions!

Load comments ↻





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