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