Q:

Scala program to create a method returning an object

belongs to collection: Scala Classes & Objects Programs

0

Here, we will create a class that contains two methods. And, we will implement a method that will return an object of the same 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 create a method returning object is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to create a method 
// returning an object

class Demo {
  def retObj(): Demo = {
    println("Method returning object");
    return this;
  }

  def sayHello() {
    println("Hello World");
  }

}

object Sample {
  def main(args: Array[String]) {
    // Create an object of Demo class
    var obj1 = new Demo()
    var obj2 = obj1.retObj();

    obj1.sayHello();
    obj2.sayHello();
  }
}

Output:

Method returning object
Hello World
Hello World

Explanation:

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

Here, we created a class Demo that contains two methods retObj() and sayHello(). The retObj() method returns the object of the same class and the sayHello() method prints the "Hello World" message on the console screen.

In the main() function, we created an obj1 object of the Demo class and called retObj() method. It returns the object, which is assigned to the obj2 object. Then we called the sayHello() method from both objects and print messages 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 pass an object as an argument... >>
<< Scala program to implement cascaded method call...