Wednesday, July 22, 2020

"this" keyword in java

"this" keyword


If instance variable and local variable name is same i.e. a=a in example, it'll print the value of instance value:



package code;

public  class ThisKeywordTest {
 int a;


 void setValue(int a) {
a=a;

}
 void show() {
System.out.println(a);
}


public static void main(String[] args) {

ThisKeywordTest ob = new ThisKeywordTest();
ob.setValue(4);  
ob.show();
}

}
o/p: 0
---------------------------------------------------------------------------------------------

To resolve the issue we'll use this keyword.

package code;

public  class ThisKeywordTest {
 int a;


 void setValue(int a) {
 this.a=a;

}
 void show() {
System.out.println(a);
}


public static void main(String[] args) {

ThisKeywordTest ob = new ThisKeywordTest();
ob.setValue(4);
ob.show();
}


}
o:p= 4




Add caption





No comments:

Post a Comment

Guitar Chords

click on   Guitar Chords Family