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