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