- This keyword is used to refer to the current class instance variable.
- This keyword is used to invoke the current class method.
- This keyword is used to invoke the current class constructor.
class Student { int rno; String name; Student(int rno,String name) { this.rno=rno; this.name=name; } void show() { System.out.println(rno+" "+name); } } class ThisKeyword { public static void main(String args[]) { Student s1=new Student(101,"Tanmay"); Student s2=new Student(102,"Shivam"); s1.show(); s2.show(); } } Output: 101 Tanmay 102 Shivam
2. To invoke the current class method:
class ThisKeyword { void a() { System.out.println("a called"); } void b() { System.out.println("b called"); this.a(); } } class This1 { public static void main(String args[]) { ThisKeyword t=new ThisKeyword(); t.b(); } } Output: b called a called
3. To invoke current class constructor:
class This1 { This1() { System.out.println("hello"); } This1(int x) { this(); System.out.println(x); } } class This2 { public static void main(String args[]) { This1 t=new This1(100); } } Output: hello 100