In java this keyword is use to reference the an object. Most of the time it used to reference the current object. However, in inner class, this can also refer to parent class with parent class name.
Simple example of this keyword
School.java
package thiskeyworddemo; public class School { String name; int teacher; int student; School(String name, int teacher ){ this.name = name; this.teacher = teacher; } School(String name, int teacher, int student ){ this(name,teacher); this.student = student; } void displayInfo(){ System.out.println("Name : "+name); System.out.println("Teacher : "+teacher); } void displayInfo2(){ this.displayInfo(); System.out.println("Student : "+student); } }
Test.java
package thiskeyworddemo; public class Test { public static void main(String[] args) { School ob = new School("Msti School",10 ,100); ob.displayInfo2(); } }
Usage of this keyword in java:
This keyword can be use to
- refer current class instance variable
- implicitly invoke current class method
- invoke current class constructor
This keyword can also be
- pass as an argument in method call
- be pass as argument in constructor call
- use to return current class instance from the method
In Inner class, this keyword is use with parent class name as prefix to refer parent class object. For example
class A{ /* Notice that class B is not static class, so it can access all the variables in parent class */ class B{ void print(){ System.out.println(A.this.name); } } String name = "Hello, I'm in class A"; }
Most of the time, when we call a method in the current class, the this keyword is there hidden. However, if the method parameter’s variable name, and the class’s variable name is same, then the variable is passed in the class’s variable using this keyword.