7.4. Object Reference this

this: this is a keyword used in instance methods to refer to the current object. In the body of the instance method, the ‘this’ reference can be used like any other object reference to access members of the object.

			package javatutorial;

			/**
			 * Example class to learn about object reference this in Java
			 *     
			 *  @author f5java.com   
			 */
			public class Keywordthis {
				
				String personName;
				int personAge;
				String personGender;
				
				/**
				 * Sets the default values
				 */
				public void setDefaultValues(){
					// 1.Lets use the this reference to set the values
					// this reference to the current object, in this case it is object of Keywordthis class
					this.personName = "Sam";
					this.personAge = 21;
					this.personGender = "male";
					
					// 2. this reference cannot be modified, coz it is final reference
			//		this = new Employee();  // Invalid, compile time error, cannot modify reference
				}


				public static void main(String[] args) {
					
					// 3. this is not available in static context
			//		this.personName = "Sam"; // Invalid, this is not available in static method
			//		this.personAge = 21;     // Also compile time error
			//		this.personGender = "male";
					
					// Instantiate and call the method
					Keywordthis thisExample = new Keywordthis();
					thisExample.setDefaultValues();
					System.out.println("Set default values using this reference");
					System.out.println("Person Name : " + thisExample.personName);
					System.out.println("Person Age : " + thisExample.personAge);
					System.out.println("Person Gender : " + thisExample.personGender);

				}
			}