Difference Between this and this() in Java
Last Updated :
12 Mar, 2021
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. For example, this.variableName;
|
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.
Java
import java.io.*;
public class Student {
private String name;
private int age;
public Student(String name, int age)
{
this .name = name;
this .age = age;
}
public void show()
{
System.out.println( "Name = " + this .name);
System.out.println( "Age = " + this .age);
}
public static void main(String[] args)
{
Student student = new Student( "Geeks" , 20 );
student.show();
}
}
|
Output
Name = Geeks
Age = 20
Now take a look at the code below which describes the use of this().
Java
import java.io.*;
public class Student {
private String name;
private int age;
public Student(String name)
{
this ( 20 );
System.out.println( "Name of Student : " + name);
}
public Student( int age)
{
System.out.println( "Age of student = " + age);
}
public Student()
{
this ( "Geeks" );
}
public static void main(String[] args)
{
Student student = new Student();
}
}
|
Output
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.
Share your thoughts in the comments
Please Login to comment...