Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.method() is referring to?

Tags:

java

this

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?

like image 202
Chris Dobkowski Avatar asked Nov 04 '13 13:11

Chris Dobkowski


1 Answers

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.

like image 129
András Hummer Avatar answered Nov 18 '22 09:11

András Hummer