Scala program to implement method overloading based on a different order of arguments

Here, we are going to learn how to implement method overloading based on a different order of arguments in Scala programming language?
Submitted by Nidhi, on July 20, 2021 [Last updated : March 11, 2023]

Method Overloading (Based on Order of Arguments)

Here, we will create a class and implement method overloading by creating methods with different order of arguments to print a specified character on the console screen.

Scala code to implement method overloading based on the different order of arguments

The source code to implement method overloading based on a different order 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 order of arguments

class Calc {
  def printChar(num: Int, ch: Char) {
    var i: Int = 0;

    while (i < num) {
      printf("%c", ch);
      i = i + 1;
    }
    println();
  }
  def printChar(ch: Char, num: Int) {
    var i: Int = 0;

    while (i < num) {
      printf("%c", ch);
      i = i + 1;
    }
    println();
  }
}

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

    obj.printChar(5, '*');
    obj.printChar('@', 4);
  }
}

Output

*****
@@@@

Explanation

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

Here, we created a class Calc. In the Calc class, we implemented method overloading by creating two PrintChar() methods with different order of arguments. The PrintChar() method is used to print the specified character 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.

Scala Classes & Objects Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.