+ 1
Can someone please explain more about what the 'this' method does. Also how would I use it in creating a method?
8 Réponses
+ 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)*/
}
}
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?
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]
*/
0
hope that helped
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.
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.
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.
- 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;
}
}