Can we return this keyword from a method in java?

Java 8Object Oriented ProgrammingProgramming

The "this" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables, and methods.

Returning “this”

Yes, you can return this in Java i.e. The following statement is valid.

return this;

When you return "this" from a method the current object will be returned.

Example

In the following Java example, the class Student has two private variables name and age. From a method setValues() we are reading values from user and assigning them to these (instance) variables and returning the current object.

public class Student {
   private String name;
   private int age;
   public Student SetValues(){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the name of the student: ");
      String name = sc.nextLine();
      System.out.println("Enter the age of the student: ");
      int age = sc.nextInt();
      this.name = name;
      this.age = age;
      return this;
   }
   public void display() {
      System.out.println("name: "+name);
      System.out.println("age: "+age);
   }
   public static void main(String args[]) {
      Student obj = new Student();
      obj = obj.SettingValues();
      obj.display();
   }
}

Output

Enter the name of the student:
Krishna Kasyap
Enter the age of the student:
21
name: Krishna Kasyap
age: 21
raja
Published on 02-Jul-2019 11:21:10
Advertisements