Goseeko blog

What is This keyword in java ?

by Bhumika

A reference variable in Java is a variable that refers to the current object of a method or constructor. The main use of this term in Java is to distinguish between class attributes and arguments with similar names.

The following are some examples of ‘this’ keyword usage:

  • This is used to refer to current class instance variables.
  • It can be used to call or start the constructor of the current class.
  • It can use as a parameter in a method call.
  • It’s possible to send it as an argument to the constructor.
  • It can be used to get the current instance of a class.

This keyword in Java uses in a variety of ways. This is a reference variable in Java that points to the current object.

Fig : working of this keyword

Example of This keyword

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 TestThis2{  

public static void main(String args[]){  

Student s1=new Student(111,”ankita”,6000f);  

Student s2=new Student(112,”sunil”,9000f);  

s1.display();  

s2.display();  

}

}  

Output 

111 ankita 6000.0

112 sunil 9000.0

Interested in learning about similar topics? Here are a few hand-picked blogs for you!

You may also like