ADVERTISEMENT
ADVERTISEMENT

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

Problem Solution:

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.

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.

Scala Trait Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.