I have a question regarding this.
statement.
Let's say I have this code right here (very stupid and useless but gets the message across):
class Calculate{
int x,y;
final int g = 5;
//Constructor
public Calculate(int a, int b) {
x = a; y = b;
}
public int sumAddG() {
return (x+y+g);
}
//comparing method
public boolean same(Calculate in) {
if(this.sumAddG() == in.sumAddG()) { // <-- This is what I am curious about
return true;
} else {
return false;
}
}
So do I have this code right? When I am using this.SumAddG()
- Am I referring to the result of the method SumAddG() using the instance variables of this
class instance?
this
refers to the actual instance whose same()
method has been invoked. Eg. take the following code:
Calculate a = new Calculate(0, 3);
Calculate b = new Calculate(0, 4);
boolean calcFlag = a.same(b);
In this case the this
in the method same()
will refer to a
while in
will refer to b
.
Update for this line: if(this.sumAddG() == in.sumAddG()) { // <-- This is what I am curious about
you have a boolean method. In if
you're evaluating a boolean expression and you return a boolean true value if the expression itself is true. This can be simplified by simply writing
return this.sumAddG() == in.sumAddG();
This will return directly the evaluation of the two instance's equality. Generally, it is considered good practice in case of boolean methods to evaluate the expression in the return line, while evaluating it in an
if (<*any boolean expression*>) {
return true;
} else {
return false;
}
structure is considered bad practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With