Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. Usage in Java:
Here is given the 6 usage of this keyword.
this keyword can be used to refer current class instance variable.
this() can be used to invoke current class constructor.
this keyword can be used to invoke current class method (implicitly)
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this keyword can also be used to return the current class instance.
Let's consider this problem:
class student
{
int id;
String name;
student(int id,String name)
{
id = id;
name = name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
student s1 = new student(1,"NameA");
student s2 = new student(2,"NameB");
s1.display();
s2.display();
}
}
Output will be:
0 null
0 null
Solution for the problem:
//example of this keyword
class Student
{
int id;
String name;
student(int id,String name)
{
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student s1 = new Student(1,"NameA");
Student s2 = new Student(2,"NameB");
s1.display();
s2.display();
}
}
Output will be:
1 NameA
2 NameB
- 18.8k
- 13
- 53
- 56