Home »
Java Programs »
Java Class and Object Programs
Java program to create a method returning an object
Learn how to create a method returning an object in Java?
Submitted by Nidhi, on March 20, 2022
Problem statement
In this program, we will create a Sample class. Here we will implement a method returning an object using the this keyword.
Java program to create a method returning an object
The source code to create a method returning an object is given below. The given program is compiled and executed successfully.
// Java program to create a method
// returning an object
class Sample {
void sayHello() {
System.out.println("Hello World");
}
Sample retObj() {
return this;
}
}
class Main {
public static void main(String args[]) {
Sample X1 = new Sample();
Sample X2 = X1.retObj();
X1.sayHello();
X2.sayHello();
}
}
Output
Hello World
Hello World
Explanation
In the above program, we created a Sample class and public class Main. The Sample class contains two methods sayHello() and retObj(). The sayHello() method is used to print the "Hello World" message and the retObj() method returns the current object using the "this" keyword.
The Main class contains a static method main(). The main() is an entry point for the program. Here, we created 2 references of Sample class and called the sayHello() method and printed the "Hello World" message.
Java Class and Object Programs »