this is a keyword in java which can be used inside a method or a constructor to refers to the current object. Except in static methods, this keyword can be used in any method to refer to current object. this keyword can be used to refer to any member variable or member method of current class.
this keyword can be used in multiple ways:
- We can declare instance variable and local variables inside a methods having same name. this can be used to differentiate between instance variable and local variable.
- this can be used to refer to current object.
- this can be used to invoke methods and constructors of current object.
- this cab be used to pass current object as parameter to a method call.
- this can be used to create copy of an object by passing it to the copy constructor.
- this can be used to return current object from a method.
Benefits of Using "this"
- Clarity in Code : Using the this keyword makes the code more readable and self-explanatory. It clearly indicates when an instance variable is being accessed or when a method of the current object is being invoked.
- Constructor Chaining : For classes with multiple constructors, this facilitates constructor chaining, enabling the reuse of initialization logic and promoting code maintainability.
- Avoiding Naming Conflicts : The primary purpose of this is to avoid naming conflicts between instance variables and method parameters. It ensures that the correct variable is referenced, reducing the chances of logical errors.
class Company { public void printReference(Company object) { System.out.println("Object Reference = " + object); System.out.println("this Reference = " + this); } } public class ThisObjectReferenceJava { public static void main(String[] args) { Company myCompany = new Company(); myCompany.printReference(myCompany); } }Output
Object Reference = Company@12a3a380 this Reference = Company@12a3a380
In above java program, we created an object named myCompany of the class Company. We then call printReferencemethod to print the reference to myCompany object and this reference of the object.
We can see that the reference of myCompany object and this is exactly same which means this contains reference of current object.
this can be used to refer to current object.
this keyword by default refers to the current object. Inside any member method, you can use this to access any member variable or to invoke any member method. This keyword is mainly used to distinguish between instance variable and local variable of same name.
this.variable will always refer to instance variable.
class MotorBike { private boolean isEngineOn = false; private void startEngine() { this.isEngineOn = true; System.out.println("Starting Engine"); } private void startMoving() { System.out.println("Bike is Moving"); } public void startBike() { this.startEngine(); this.startMoving(); } } public class ThisJava { public static void main(String[] args) { MotorBike myBike = new MotorBike(); myBike.startBike(); } }Output
Starting Engine Bike is Moving
In above java program, we are using this to access the member variable and member methods of current object within a method body.
- Inside method startEngine, we are using this to access member variable isEngineOn of current object.
- Inside method startBike, we are using this to call two private methods startEngine and startMoving of current onject.
Using this to pass current object as method parameter
We can use this keyword to pass the current object as an argument to a method.
class Book { String name; int price; Book(String name, int price) { this.name = name; this.price = price; } public void incrementPrice(int increaseBy) { System.out.println("Before price = " + this.price); addToPrice(this, increaseBy); System.out.println("After price = " + this.price); } private void addToPrice(Book book, int amount) { book.price += amount; } } public class ThisMethodArgumentJava { public static void main(String[] args) { Book javaBook = new Book("Java Book", 100); javaBook.incrementPrice(20); } }Output
Before price = 100 After price = 120
In above program, we are passing this as argument for addToPrice method of Book. We can pass this as argument to a method which expects an object reference as argument. Since this contains the reference of object javaBook, we can access the member variables of object javaBook inside addToPrice method.
Returning current object from a method
Whenever we want to return current object reference from a member method then we can simply return this.
class Complex { int real, imaginary; public Complex setReal(int real) { this.real = real; return this; } public Complex setImaginary(int imaginary) { this.imaginary = imaginary; return this; } public void print() { System.out.format("%d + %di\n", this.real, this.imaginary); } } public class ThisMethodReturnJava { public static void main(String[] args) { Complex number = new Complex(); number.print(); number.setReal(10).setImaginary(5).print(); } }Output
0 + 0i 10 + 5i
In above example, setReal and setImaginary method return reference of current object by returning this. The caller of these two methods can use the return value as the object reference of number.
this is used for constructor overloading
Using this we can call the constructor of a class like this(). this can also be used inside a constructor to invoke another overloaded constructor of same Class, this is called constructor overloading.
For example:
Let's say a class has one constructor without any argument and one constructor with one argument. From no-argument constructor we can call one argument constructor by passing some default value.
class Rectangle { int length, width; // No-Arg Construtor Rectangle() { this(0, 0); } // One Arg Construtor Rectangle(int size) { this(size, size); } // All Arg Construtor Rectangle(int length, int width) { this.length = length; this.width = width; } public void print() { System.out.format("Length= %d, Width= %d\n", this.length, this.width); } } public class ThisConstructorOverloading { public static void main(String[] args) { Rectangle rect1 = new Rectangle(); Rectangle rect2 = new Rectangle(5); Rectangle rect3 = new Rectangle(10, 20); rect1.print(); rect2.print(); rect3.print(); } }Output
Length= 0, Width= 0 Length= 5, Width= 5 Length= 10, Width= 20
Conclusion
The this keyword is a powerful tool in Java for disambiguating between instance variables and method parameters, accessing the current object's members, and facilitating constructor chaining. By using this judiciously, developers can write cleaner, more readable code that avoids naming conflicts and enhances code maintainability. Understanding the nuances and best practices associated with the this keyword is essential for effective Java programming, and incorporating it into your coding practices will contribute to the overall quality of your code.