Q:

Scala program to implement method overloading based on the different number of arguments

belongs to collection: Scala Classes & Objects Programs

0

Here, we will create a class and implement method overloading by creating methods with the different numbers of arguments to add integer numbers and print the result on the console screen.

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 implement method overloading based on the different number of arguments is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to implement method overloading 
// based on different number of arguments

class Calc {
  def AddNumbers(num1: Int, num2: Int) {
    var result: Int = 0;

    result = num1 + num2;
    printf("Sum of two numbers is: %d\n", result);
  }
  def AddNumbers(num1: Int, num2: Int, num3: Int) {
    var result: Int = 0;

    result = num1 + num2 + num3;
    printf("Sum of three numbers is: %d\n", result);
  }
}

object Sample {
  def main(args: Array[String]) {
    var obj = new Calc();

    obj.AddNumbers(10, 20);
    obj.AddNumbers(10, 20, 30);
  }
}

Output:

Sum of two numbers is: 30
Sum of three numbers is: 60

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 Calc. In Calc class, we implemented method overloading by creating two AddNumbers() methods with different numbers of arguments. The odd numbers() method is used to add specified numbers of arguments and print the result on the console screen.

In the main() function, we created an object of the Calc class and called both methods with arguments, and printed the result 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 call constructor using \'thi...