Hi, is there any difference if I did not put the keyword this in
public double getAmount() {
return this.amount;
}
A quick question
Resolved
Comments (10)
- Popular
- New
- Old
You must be signed in to leave a comment
Karas Backend Developer
11 March 2021, 20:36solution
Yes, there might be what is called ambiguity, the computer might not be able to tell if you are calling the object variable or the class variable, this, calls only the present object. But also you could just call the full name for the variable, you know, return Euro.amount;, or USD.amount; or Ruble.amount; this way the computer know specifically what is beinig refered to.
+2
Guadalupe Gagnon
11 March 2021, 20:44
The variable amount is not static so you can't call amount in a static context (eg: ClassName.variableName). None of these work:
Euro.amount
USD.amount
Ruble.amount
+3
Karas Backend Developer
11 March 2021, 20:53
You are right.
0
Gellert Varga
11 March 2021, 00:15
The this.amount variable and the "double amount" declared in the parentheses are two different variables. Just their names are the same, but they are not the same.
Somehow you should make a distinction between them.
You can use the keyword "this" to indicate that we are talking about a variable of the current ("this") object, as opposed to the "double amount" variable declared in the method, which is a local variable.
But the method or constructor above can work also this way, without using "this". (But to write the code this way i don't know is it good idea or not. But it works.) :
+3
Mina Nabil
11 March 2021, 00:44
Sorry Gellert, it seems that I wrote the wrong code, I meant
public double getAmount() {
return this.amount;
}
I already edited the question now.
0
Guadalupe Gagnon
11 March 2021, 05:01solution
Gellart answer still applies to that. The keyword 'this' always refers to the current object and is used for 2 purposes:
1) as a return when you are to return the current object
2) as a way to get the class field when a local variable has the same name (as Gellert said).
In the getAmount() class you are not returning the current object and there is not a local variable called "amount", so the keyword 'this' is not needed.
+4
Mina Nabil
12 March 2021, 10:39
"In the getAmount() class you are not returning the current object and there is not a local variable called "amount", so the keyword 'this' is not needed."
I think I am returning the current object amount, so I did not understand this sentence.
0
Guadalupe Gagnon
12 March 2021, 14:13
Variable 'amount' is not the current object, it is only a variable in the current object. Keyword 'this' refers to the whole current object, which is a valid thing you can return, and not its contents.
+2
Mina Nabil
12 March 2021, 14:36
I mean, we are returning the current object amount variable, right ?
0
Guadalupe Gagnon
12 March 2021, 14:41
but you don't need 'this' unless you are returning the whole object, as in:
+2