×

Java Programs

Java Practice

Java program to implement cascaded method call with an anonymous object

Learn how to implement cascaded method call with an anonymous object in Java?
Submitted by Nidhi, on March 25, 2022

Problem statement

In this program, we will create a class with three methods. Then we will create an anonymous object and call its methods in a cascaded manner.

An object which has no reference variable is called an anonymous object.

Source Code

The source code to implement a cascaded method call with an anonymous object is given below. The given program is compiled and executed successfully.

// Java program to implement cascaded method call 
// with the anonymous object

class Sample {
  Sample Method1() {
    System.out.println("Method1 called");
    return this;
  }

  Sample Method2() {
    System.out.println("Method2 called");
    return this;
  }

  Sample Method3() {
    System.out.println("Method3 called");
    return this;
  }
}
public class Main {
  public static void main(String[] args) {
    new Sample().Method1().Method2().Method3();
  }
}

Output

Method1 called
Method2 called
Method3 called

Explanation

In the above program, we created two classes Sample and Main. The Sample class contains three methods Method1(), Method2(), Method3(). All methods return the reference of class using the "this" keyword.

The Main class contains a method main(). The main() method is the entry point for the program, here we created an anonymous object of the Sample class and called methods in a cascaded manner.

Java Class and Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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