Q:

Scala program to demonstrate the \'this\' keyword

belongs to collection: Scala Classes & Objects Programs

0

Here, we will create a class with two data members. And, we will also define two methods, there we will use the this keyword to differentiate the member of the class and the parameters of the method. The this keyword is always used to represent the member of the class.

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 demonstrate this keyword is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to demonstrate "this" keyword

class Demo {
  var num1: Int = 0;
  var num2: Int = 0;

  def setValues(num1: Int, num2: Int) {
    this.num1 = num1;
    this.num2 = num2;
  }

  def printValues() {
    printf("Num1: %d\n", this.num1);
    printf("Num2: %d\n", this.num2);
  }
}

object Sample {
  def main(args: Array[String]) {
    // Create an object of Demo class
    var obj = new Demo()
    obj.setValues(100, 200);
    obj.printValues();
  }
}

Output:

Num1: 100
Num2: 200

Explanation:

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

Here, we created a class Demo with two members num1 and num2. The Demo class contain two methods setValues() and printValues(). The name parameters of setValues() method and data members are the same. That's why we used this keyword to differentiate parameters and data members. The this keyword is used with data members of the class.

In the main() function, we created an object of the Demo class and then set and print the value of data members.

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

total answers (1)

Scala program to implement cascaded method call... >>
<< Scala program to create a private case class...