but Java is clever enough to know what is happening if I change the statement in the constructor to
bar = bar;
FALSE! It compiles but it doesn't do what you think it does!
As to when to use it, a lot of it is personal preference. I like to use this in my public methods, even when it's unnecessary, because that's where the interfacing happens and it's nice to assert what's mine and what's not.
As reference, you can check the Oracle's Java Tutorials out about this.subject ;-)
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
Answer from polygenelubricants on Stack OverflowVideos
but Java is clever enough to know what is happening if I change the statement in the constructor to
bar = bar;
FALSE! It compiles but it doesn't do what you think it does!
As to when to use it, a lot of it is personal preference. I like to use this in my public methods, even when it's unnecessary, because that's where the interfacing happens and it's nice to assert what's mine and what's not.
As reference, you can check the Oracle's Java Tutorials out about this.subject ;-)
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
You should use it when you have a parameter with the same name as a field otherwise you will run into issues. It will compile, but won't necessarily do what you want it to.
As for everywhere else, don't use it unless it's needed for readability's sake. If you use it everywhere, 20% of your code will consist of the word 'this'!
can someone help me out on better understanding on when to use the this. keyword ?
I have this code right here:
public class ATM {
public static int totalMoney = 0;
public static int numATMs = 0;
public int money;
public ATM(input money){
this.money = inputMoney;
numATMs += 1;
totalMoney += inputMoney;
}
public void withdrawMoney(int amountToWithdraw){
if (amountToWithdraw <= this.money){
this.money -= amountToWithdraw;
totalMoney -= amountToWithdraw;
}
}
public static void main(String[] args) {
System.out.println
}
}and i understand the majority of this right here. However the part that im not understanding is this part:
public void withdrawMoney(int amountToWithdraw){
if (amountToWithdraw <= this.money){
this.money -= amountToWithdraw;
totalMoney -= amountToWithdraw;
}
}to my understanding, the word this. basically says "we are using THIS variable, in this case money within this method" and the reason that we don't have THIS on amountToWithdraw is basically a global variable that we are accessing ?
sorry for the dumb question. please don't roast me too hard :(