Can we call methods using this keyword in java?



The "this" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Yes, you can call methods using it. But, you should call them only from instance methods (non-static).

Example

In the following example, the Student class has a private variable name, with setter and getter methods, using the setter method we have assigned value to the name variable from the main method and then, we have invoked the getter (getName) method using "this" keyword from the instance method.

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

Output

Enter the name of the student:
Krishna
name: Krishna
raja
Published on 02-Jul-2019 14:41:12
Advertisements