Java - Use this to call method

Introduction

You can use this keyword to call an instance method.

class Student {
  void m1() {
    // Invoke the m2() method
    this.m2(); // same as "m2();"
  }

  void m2() {
    System.out.println("n2");
  }

}

The following code shows how to invoke m2() via m1()

Demo

class Student {
  void m1() {//from w  ww .  j a v a  2 s.c  o m
    // Invoke the m2() method
    this.m2(); // same as "m2();"
  }

  void m2() {
    System.out.println("n2");
  }

}

public class Main {
  public static void main(String[] args) {
    Student s = new Student();

    s.m1();
  }
}

Result

Related Topic