Q:

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

belongs to collection: Scala Trait Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala program to create a non-abstract method insi... >>
<< Scala program to create a simple trait...