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

Problem Solution:

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

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) {
    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)


Num1: 200
Num2: 300


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



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

© some rights reserved.