This Keyword
Note − The keyword this is used only within instance methods or constructors

In general, the keyword this is used to −
class Student {
int age;
Student(int age>
{
this.age = age;
}
}
from other in a class. It is known as explicit constructor invocation.
class Student {
int age
Student(>
{
this(20>
;
}
Student(int age>
{
this.age = age;
}
}
Example :
Here is an example that uses this keyword to access the members of a class. Copy and paste the following program in a file with the name, This_Example.java.
public class This_Example {
// Instance variable num
int num = 10;
This_Example(>
{
System.out.println("This is an example program on keyword this">
;
}
This_Example(int num>
{
// Invoking the default constructor
this(>
;
// Assigning the local variable num to the instance variable num
this.num = num;
}
public void greet(>
{
System.out.println("Hi Welcome to TechedHub">
;
}
public void print(>
{
// Local variable num
int num = 20;
// Printing the local variable
System.out.println("value of local variable num is : "+num>
;
// Printing the instance variable
System.out.println("value of instance variable num is : "+this.num>
;
// Invoking the greet method of a class
this.greet(>
;
}
public static void main(String[] args>
{
// Instantiating the class
This_Example obj1 = new This_Example(>
;
// Invoking the print method
obj1.print(>
;
// Passing a new value to the num variable through parametrized constructor
This_Example obj2 = new This_Example(30>
;
// Invoking the print method again
obj2.print(>
;
}
}
Output :
