Scala program to create an abstract class with the constructor

Here, we are going to learn how to create an abstract class with the constructor in Scala programming language?
Submitted by Nidhi, on July 07, 2021 [Last updated : March 11, 2023]

Scala – Abstract Class with Constructor Example

Here, we will demonstrate the use of abstract class with the constructor. An abstract class contains the declaration of methods. To implement the abstract methods, we need to inherit the abstract class into a class.

Scala code to demonstrate the example of abstract class with the constructor

The source code to create an abstract class with a data constructor is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to create an abstract class 
// with the constructor

abstract class Demo1(num1: Int, num2: Int) {
  def printValues();
}

class Demo2(num1: Int, num2: Int) extends Demo1(num1, num2) {
  def printValues() {
    printf("Num1: %d\n", num1);
    printf("Num2: %d\n", num2);
  }
}

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

    obj.printValues();
  }
}

Output

Num1: 10
Num2: 20

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 is an abstract class with a primary constructor, it contains an abstract method printValues(). Then we inherited the Demo1 class into the Demo2 class and implemented the printValues() method. And, we called the constructor of class Demo1 from the constructor of Demo2.

In the main() function, we created the object of the Demo2 class and called the primary constructor to initialize data members. After we called the printValues() method to print the values of num1 and num2 on the console screen.

Scala Abstract Classes Programs »






Comments and Discussions!

Load comments ↻






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