 Humgaorange
join:2004-12-08 North York, ON
| this
Can someone please explain it to me what is "this". I looked for so many websites, and i still don't get it 
Here's an example
class Numbers { private int aNumber = 42;
public int returnANumber() { return this.aNumber; } public int returnANumber(int intIn) { return (intIn * this.returnANumber()); } public static void main(String[] args) { Numbers numberTest = new Numbers();
System.out.println("The Number is " + numberTest.returnANumber() ); //output is: The Number is 42 System.out.println("The Number is " + numberTest.returnANumber(2) ); //output is: The Number is 84 } }
I tried to replace this.aNumber to aNumber and this.returnANumber to aNumber and still work .. so why do we need "this" ? |
|
  GILXA1226 Premium,MVM join:2000-12-29 London, OH clubs: | Actually... in this case I don't think the 'this' is needed. 'this' generally refers to the current instance of a class or struct. -- O! - H! ..... I! - O! |
|
 Humgaorange
join:2004-12-08 North York, ON | Can you please give me an example, because I still don't really understand  |
|
  javaMan Premium,MVM join:2002-07-15 San Luis Obispo, CA
| reply to Humgaorange The this reserved or keyword is used to refer to the current object or class or more precisely to the recipient of the method in which the keyword appears. You can think of it a short cut reference of sorts. There are many uses for it. For example, it can be used when method overloading is employed. To illustrate, the example below, from an old text book I have laying on a shelf, shows how it can be used for class constructors.
public class IntRectangle { // Data fields int width; // input - essential attribute int length; // input - essential attribute
// Constructors public IntRectangle() { }
public IntRectangle(int w, int l) { width = w; length = l; }
public IntRectangle(int side) { this(side, side); } } -- Woe unto them that call evil good, and good evil; that put darkness for light, and light for darkness. . . Isa. 5:20 |
|
 Humgaorange
join:2004-12-08 North York, ON | Thank You all !  |
|