“this” keyword in Hindi
this keyword एक reference variable है जिसका प्रयोग किसी एक method या constructor में current object को refer करने के लिए किया जाता है.
जब program में Instance variable और Local variable दोनों same ही होते है | इसीलिए जब instance variable(left) की value; local variable(right) पर assign की जाती है, तब compiler को समझ नहीं आता कि, कौनसा variable; instance है और कौनसा variable local है | इसलिए हम this keyword का उपयोग करते है जिससे compiler आसानी से समझ सके कौन instance variable है और कौन local variable।
जब हम program में Instance variable और Local variable दोनों same ही रखते है |
class Sample{
int a; // instance variable
int b; // instance variable
Sample(int a, int b){ // a and b is local variable
a = a;
b = b;
}
void show(){
System.out.println("Value of a : " + a);
System.out.println("Value of b : " + b);
}
public static void main(String args[]){
Sample s = new Sample(5, 6);
s.show();
}
}
OUTPUT :
Value of a : 0
Value of b : 0
Program में this keyword के साथ Instance variable और Local variable इन दोनों variables को अलग-अलग किया गया है |
class Sample{
int a; // instance variable
int b; // instance variable
Sample(int a, int b){ // a and b is local variable
// using this keyword
this.a = a; //Instance Variable = Local Variable;
this.b = b; //Instance Variable = Local Variable;
}
void show(){
System.out.println("Value of a : " + a);
System.out.println("Value of b : " + b);
}
public static void main(String args[]){
Sample s = new Sample(5, 6);
s.show();
}
}
OUTPUT :
Value of a : 5
Value of b : 6
Usage of java this keyword
- इसका प्रयोग current class के instance variable को refer करने के लिए किया जाता है.
- इसका प्रयोग current class के method को invoke करने के लिए किया जाता है.
- current class constructor को invoke करने के लिए भी इसका use होता है.
- इसको method call में argument के रूप में pass कर सकते हैं.
- इसको constructor call में argument के रूप में pass कर सकते हैं.
- इसका प्रयोग method से current class instance को return करने के लिए किया जाता है.
references:- https://www.javatpoint.com/this-keyword
RECOMMENDED POST :