this keyword in Java
There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object.
Usage of Java this keyword
Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
1) this: to refer current class instance variable
Example:-
class Student
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
this.rollno=rollno;
this.name=name;
this.fee=fee;
void display()
{
System.out.println(rollno+" "+name+" "+fee);
class Test
public static void main(String args[])
Student s1=new Student(111,”ankit”,5000f);
Student s2=new Student(112,”sumit”,6000f);
s1.display();
s2.display();
2) this: to invoke current class method
This keyword is used to invoke the method of the current class. If you don't
use the this keyword, compiler automatically adds this keyword while
invoking the method.
class A
void m()
System.out.println("hello m");
}
void n()
System.out.println("hello n");
this.m();
class Test
public static void main(String args[])
A a=new A();
a.n();
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class
constructor. It is used to reuse the constructor. In other words, it is used for
constructor chaining.
Example:- Calling default constructor from parameterized constructor
class A
A()
System.out.println("hello a");
}
A(int x)
this();
System.out.println(x);
class Test
public static void main(String args[])
A a=new A(10);
Example:- Calling parameterized constructor from default constructor
class A
A()
this(5);
System.out.println("hello a");
A(int x)
{
System.out.println(x);
class Test
public static void main(String args[])
A a=new A();