|
|
The keyword this is used inside non-static/object methods as a reference to the object to which the method belongs from within the object itself—a reference to itself. For example, take a look at the constructor for the Alien class that we have just declared where we used the keyword this.
public Alien(String greeting) { this.greeting = greeting; }
We have given the String parameter of the constructor the same name as one of the members of the class, calling both variables greeting. This is possible in Java and means that any use of the identifier will be in reference to the local variable greeting that is a parameter of the constructor. In this case, we need some way to access the greeting member of the class and not the parameter value, so we can use the keyword this, which will act as a reference to the current object to which the constructor belongs. The keyword this can be used in non-static methods in the same way as in the constructor of the Alien class.
Note | Just in case this has misled you slightly, the name of the parameter variable did not need to be called greeting. It is called greeting to illustrate a situation where you would need to use the keyword this, but it can be any name you like. Some people prefer to give parameters the same name as members of the class and then use the keyword this as appropriate, whereas others will give the parameter a different name altogether, maybe by using a naming convention, such as starting all parameter names with an underscore (_). The latter is obviously the least error-prone. public Alien(String _greeting) { greeting = _greeting; } Because there is no local variable called greeting, the keyword this is not required, though it can still be used anyway. |
The keyword can be used in many areas. Another notable area is passing a reference for the current object you are in as a parameter to a method. For example, you may have a static method somewhere for printing to the console window the greeting of an Alien object, as follows.
public static void printGreeting(Alien alien) { System.out.println(alien.greeting); }
From inside an object method (an object method being a non-static method) of the Alien class, we could call this method as follows.
printGreeting(this);
Basically, we are in a method that belongs to the Alien object, and we need to send a reference to the method printGreeting of the object that we are currently in, which of course is of type Alien, so we use the keyword this, passing it as a parameter as shown.
|
|