# Java Question :D

• 03-12-2010, 04:29 PM
thisisIT
Java Question :D
// method in adding Polynomials that will return c = a + b
Polynomial a = this;
Polynomial c = new Polynomial(0, Math.max(a.deg, b.deg));
for (int i = 0; i <= a.deg; i++) c.coef[i] += a.coef[i];
for (int i = 0; i <= b.deg; i++) c.coef[i] += b.coef[i];
c.deg = c.degree();
return c;
}

//method in subracting Polynomials that will return c = (a - b)
public Polynomial subtract(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(0, Math.max(a.deg, b.deg));
for (int i = 0; i <= a.deg; i++) c.coef[i] += a.coef[i];
for (int i = 0; i <= b.deg; i++) c.coef[i] -= b.coef[i];
c.deg = c.degree();
return c;
}

//method in Multiplying Polynomails that will return c = (a * b)
public Polynomial multiply(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(0, a.deg + b.deg);
for (int i = 0; i <= a.deg; i++)
for (int j = 0; j <= b.deg; j++)
c.coef[i+j] += (a.coef[i] * b.coef[j]);
c.deg = c.degree();
return c;
}

-Just want to ask whats the purpose of Polynomial a = "this" <--- why this .
• 03-12-2010, 04:34 PM
sky
this referrs to the object itself, so it is a binding to operate with that instance of the object and another Polynomial object.
• 03-12-2010, 04:39 PM
thisisIT
in the source code, why he used "this"?
• 03-12-2010, 04:43 PM
Fubarable
Quote:

in the source code, why he used "this"?

There's no absolute need to use this in the code above if you reference the object's data directly:

Code:

```public Polynomial add(Polynomial b) {   //Polynomial a = this;   Polynomial c = new Polynomial(0, Math.max(deg, b.deg));   for (int i = 0; i <= deg; i++) c.coef[i] += coef[i];   for (int i = 0; i <= b.deg; i++) c.coef[i] += b.coef[i];   c.deg = c.degree();   return c; }```
but I'll bet that this is being used for cleanliness and symmetry.

Much luck.
• 03-12-2010, 04:46 PM
JosAH
Quote:

Originally Posted by thisisIT
in the source code, why he used "this"?

You could've written, say, the add( ... ) method like this:

Code:

```public Polynomial add(Polynomial b) { Polynomial c = new Polynomial(0, Math.max(deg, b.deg)); for (int i = 0; i <= deg; i++) c.coef[i] += coef[i]; for (int i = 0; i <= b.deg; i++) c.coef[i] += b.coef[i]; c.deg = c.degree(); return c; }```
... but the difference are futile; in the original version the variable 'a' is just an alias for 'this'; maybe it meets the comments a bit better, i.e. add polynomials a+b

kind regards,

Jos
• 03-12-2010, 05:01 PM
thisisIT
Thanks Guys :D Got it.
Sorry just new in java.
Thanks Sir Jos & Faburable . :)

*Idk to close this thread. lol *
• 03-12-2010, 05:04 PM
Fubarable
Quote:

Originally Posted by thisisIT
Thanks Guys :D Got it.
Sorry just new in java.
Thanks Sir Jos & Faburable . :)

There is absolutely nothing wrong with being new, with asking questions and trying to learn.

Quote:

*Idk to close this thread. lol *