Here, we will create a class that contains three methods. Each method will return the object of the same class. To return the object of the class, we used this object. By returning an object from each method, we can implement a cascaded method call.
The source code to implement the cascaded method call is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
// Scala program to implement cascaded method call
class Demo {
def method1(): Demo = {
println("Method1 called");
return this;
}
def method2(): Demo = {
println("Method2 called");
return this;
}
def method3(): Demo = {
println("Method3 called");
return this;
}
}
object Sample {
def main(args: Array[String]) {
// Create an object of Demo class
var obj = new Demo()
//Cascaded method call.
obj.method1().method2().method3();
}
}
Output:
Method1 called
Method2 called
Method3 called
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 three methods Method1(), Method2(), Method3(). All methods return the object of the same class using this object to implement the cascaded method class.
In the main() function, we created an object of the Demo class and then call all methods using the single object in a single line.
Program/Source Code:
The source code to implement the cascaded method call 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 with three methods Method1(), Method2(), Method3(). All methods return the object of the same class using this object to implement the cascaded method class.
In the main() function, we created an object of the Demo class and then call all methods using the single object in a single line.
need an explanation for this answer? contact us directly to get an explanation for this answer