“this” Keyword
Hey everyone, in today’s reading i will be explaining “this” keyword.
This keyword has a few usages in Java, today i am not going to explain and show all usages of the keyword but i am going to explain some of them.
1-Referring current class instance variable
In some situations we declare the name of the constructor parameters and the name of the instance variables same and that could create a confusion, “this” keyword helps about that.
For Example
public class Student {
int number;
String name;Student(int number,String name){
number=number;
name=name;
}}
In this code we created a student class and declared two attributes, but the constructor parameter names are same with the attribute names.
public class Student {
int number;
String name;Student(int number,String name){
this.number=number;
this.name=name;
}
}
With the help of this keyword we can refer the instance variables.
2-Invokes current class method
public class Student { void printNum() {
System.out.println(17);
}
void testMet() {
System.out.println(16);
this.printNum();
}
}
class Test{
public static void main(String[] args) {
Student st=new Student();
st.testMet();
}
}
In this example i have created two methods and called only one in the main method but since i used this it called the other method.
3-Invokes the constructor
Same as the previous one we can call the constructor by using “this” keyword.
public class Student { Student(){
System.out.print("Hi ");
}
Student(String name){
this();
System.out.println(name);
}
}
class Test{
public static void main(String[] args) {
Student st=new Student("Baran");
}
}
4-Returns instance of class
In some cases if the return type of a method is the same as the class type we can use this to return the instance of the class.
public class Student {
String name="Baran";
Student getStudent() {
return this;
}
}
class Test{
public static void main(String[] args) {
System.out.println(new Student().getStudent().name);
}
}
As you can see we can access as the attributes and we can even access the methods using this as an instance.
In conclusion, this keyword is sometimes being very useful for some situations, my favorite usage of this keyword is number one by the way :)
Thanks for reading, see you on the next writing.