Q:

Scala program to call constructor using \'this\' keyword

belongs to collection: Scala Classes & Objects Programs

0

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

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

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

total answers (1)

Scala program to implement method overloading base... >>
<< Scala program to pass an object as an argument...