Scala program to call constructor using 'this' keyword

Here, we are going to learn how to call constructor using 'this' keyword in Scala programming language?
Submitted by Nidhi, on July 20, 2021 [Last updated : March 11, 2023]

Scala – Calling Constructor (Using 'this' Keyword)

Here, we will create a class and call the constructor of the class using the 'this' keyword.

Scala code to call constructor using 'this' keyword

The source code to call constructor using this keyword is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to call constructor
// using "this" keyword

class Demo(num1: Int) {
  def this(num1: Int, num2: Int) {
    this(num1);
    printf("Num1: %d\n", num1);
    printf("Num2: %d\n", num2);
  }
}

object Sample {
  def main(args: Array[String]) {
    // Create an anonymous object of Demo class
    new Demo(200, 300)
  }
}

Output

Num1: 200
Num2: 300

Explanation

In the above program, we used an object-oriented approach to create the program. And, we created an object Sample.

And, we created a class Demo and implemented a constructor using the this keyword to set and print the value of data members num1 and num2.

In the main() function, we created an anonymous object of the Demo class and print the value of data members on the console screen.

Scala Classes & Objects Programs »





Comments and Discussions!

Load comments ↻





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