In Java, both this and this() are completely different from each other.
- this keyword is used to refer to the current object, i.e. through which the method is called.
- this() is used to call one constructor from the other of the same class.
The below table shows the point-to-point difference between both this keyword and this().
this | this() |
---|---|
this keyword is used with the objects only. |
this() is used with constructors only. |
It refers to the current object. |
It refers to the constructor of the same class whose parameters matches with the parameters passed to this(parameters). |
Dot(.) operator is used to access the members. |
No Dot(.) operator is used. Only the matching parameters are passed. |
It is used to differentiate between the local variable and the instance variable in the method. |
It is used to refer to the constructor belonging to the same class. |
See the code below, which describes the utilization of this keyword.
import java.io.*;
public class Student {
private String name;
private int age;
// Note that in the Constructor below "this keyword" is
// used to differentiate between the local variable and
// the instance variable.
public Student(String name, int age)
{
// Assigns the value of local name variable
// to the name(instance variable).
this .name = name;
// Assigns the value of local Age variable
// to the Age(instance variable).
this .age = age;
}
public void show()
{
System.out.println( "Name = " + this .name);
System.out.println( "Age = " + this .age);
}
public static void main(String[] args)
{
// Creating new instance of Student Class
Student student = new Student( "Geeks" , 20 );
student.show();
}
} |
Name = Geeks Age = 20
Now take a look at the code below which describes the use of this().
import java.io.*;
public class Student {
private String name;
private int age;
// Constructor 1 with String as parameter.
public Student(String name)
{
// This line of code calls the second constructor.
this ( 20 );
System.out.println( "Name of Student : " + name);
}
// Constructor 2 with int in parameter.
public Student( int age)
{
System.out.println( "Age of student = " + age);
}
// Constructor 3 with no parameters.
public Student()
{
// This line calls the first constructor.
this ( "Geeks" );
}
public static void main(String[] args)
{
// This calls the third constructor.
Student student = new Student();
}
} |
Age of student = 20 Name of Student : Geeks
Please note that this() should always be the first executable statement in the constructor. Otherwise, the program will give compile time error.