Can someone please explain more about what the 'this' method does. Also how would I use it in creating a method? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can someone please explain more about what the 'this' method does. Also how would I use it in creating a method?

14th Jul 2016, 9:54 AM
Bob N.
8 Answers
+ 1
firstly don't confuse with "this" keyword and "this()" method. these two are totally different. I am putting an example for "this" key word class MyClass { int i; //class variable void myMethod(int i) { //i = i; /*this will not work since both the variable has same name*/ this.i = i; /* so "this" keyword is used when you have same named variable(one should be class variable and one should be local variable)*/ } }
14th Jul 2016, 11:16 AM
Dhiman Das
Dhiman Das - avatar
0
Ok, but what is the benefit of using such a method, and how can it help in creating a setter or getter method for a class?
14th Jul 2016, 10:16 AM
Bob N.
0
/* private class EX { private int classA; private int number; private ArrayList <Integer> list; //constructor //A=0 number =8 //A=1 number=9 public EX(int A, int number) { // by say this, I am refer to the classA and number fields in this exact class. this.classA = A; this.number = number; } /* client will not have access to this method only way client can talk to method is through constructor */ private static setNumbers (){ list. set (this.classA, this.number); } } out put of array is printed list [8,9] */
14th Jul 2016, 10:40 AM
michael edia
michael edia - avatar
0
hope that helped
14th Jul 2016, 10:40 AM
michael edia
michael edia - avatar
0
Ok. I get it now. So the "this" word is helps when you have two variables of the same name and want to make sure both are defined clearly.
14th Jul 2016, 11:22 AM
Bob N.
0
this() is used to call the current class constructor and only this keyword is used to refer to current class object. when you call some method in another method compiler impliciltly adds this keyword before called method.
15th Jul 2016, 5:00 AM
Yatin Gaikwad
0
'this' is like a pointer pointing from the constructor to an instance of object to help us access the private field of the member variable.
15th Jul 2016, 3:18 PM
Ablelom
Ablelom - avatar
- 1
this method means you are referring to that exact class or element your in and it can also refer to the private field in such class. example private class EX { private int classA; private int number; public EX(int A, int number) { // by say this, I am refer to the classA and number fields in this exact class. this.classA = A; this.number = number; } }
14th Jul 2016, 10:11 AM
michael edia
michael edia - avatar