Java – what is the best practice for using “this” in classes in OOP?
•
Java
What I've been thinking about is the preferred course in which you can use 'this [name]' or a simple [name] reference member?
For example, in Java:
public class foo {
public int bars = 0;
private void incrementBars(){
bars++;
}
}
and
public class foo {
public int bars = 0;
private void incrementBars(){
this.bars++;
}
}
"Seems" to have the same effect
In the case where I instantiate multiple instances of class foo, so far, I will do something similar to
for (foo f : listOfFoos){
f.incrementBars();
}
It still seems to work
Is this technically ambiguous?
Solution
Use this in the case of variable shadowing
class MyClass{
int i;//1
public void myMethod(){
i = 10;//referring to 1
}
public void myMethod(int i){//2
i = 10;//referring to 2
this.i = 10 //refering to 1
}
}
Sometimes this will make the code more readable because of our English mentality
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
