Use of “this” Keyword in Java

Updated on July 2, 2024

Article Outline

In Java programming, the ‘this’ keyword appears as a universal tool, wielding a number of benefits. Acting as a beam of hope amidst the complexities of code, ‘this’ navigates through potential naming clashes, ensuring smooth sailing by distinguishing between parameters and instance variables. Its prowess extends beyond mere functionality; ‘this’ enhances the readability of code, transforming intricate hierarchies into narratives of clarity. 

 

Through its ingenious invocation of constructors within the same class, ‘this’ engineers a symphony of efficiency, minimising redundancy and promoting a culture of code reuse. Yet, its most profound impact lies in fortifying the bastions of encapsulation, shielding variables from unintended alterations and empowering developers with a newfound sense of control. In the huge web of Java, the ‘this’ keyword emerges not just as a mere syntactic construct but as a beacon of ingenuity, illuminating the path towards elegance and efficiency in programming.

 

What are Java Keywords?

 

Java keywords, also referred to as reserved words, serve as specific identifiers within code. These predefined terms in Java hold special significance and cannot be utilised as variable, object, or class names due to their reserved status.

 

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

What is “this”  keyword in Java?

 

The keyword ‘this’ is employed to denote the method associated with the current object. In every class, there exist variables and methods, which can be of local, static, or instance types inherited from the superclass. For instance, variables are declared within the class but outside of methods, enabling access through objects with the utilisation of the ‘this’ keyword.

 

Features of this” keyword in Java

 

Below lie pivotal characteristics of the ‘this’ keyword within Java:

 

– It serves to reference the instance variable of the current class.

– It facilitates the invocation of the current class method.

– It enables the invocation of the current class constructor.

– It holds the capability to be transmitted as an argument during method calls.

Uses of “this” keyword

 

Here are some of the basic uses of “this” keyword in Java:

 

  • Use of “this” keyword in Java to access the instance variables

 

Code: 

 

class Person {

   private String name;

   private int age;

   public Person(String name, int age) {

       this.name = name;

       this.age = age;

   }

   public void printDetails() {

       System.out.println(“Name: ” + this.name);

       System.out.println(“Age: ” + this.age);

   }

}

class Main{

  public static void main(String args[]){

     Person person = new Person(“PrepBuddy”, 18);

     person.printDetails();

  }

}

 

Output:

 

Name: PrepBuddy

Age: 18

 

Explanation: Within the provided code, the ‘printDetails()’ method employs the ‘this’ keyword in Java to access the ‘name’ and ‘age’ instance variables of the current Person object. This utilisation is essential due to the presence of name and age parameters within the method, which could potentially obscure the instance variables otherwise.

 

  • Use of “this” keyword in Java to invoke another constructor in the same class

 

Code:

 

class Rectangle {

   private int width;

   private int height;

   public Rectangle(int sideLength) {

       this(sideLength, sideLength);

   }

   public Rectangle(int width, int height) {

       this.width = width;

       this.height = height;

   }

   public int getArea() {

       return this.width * this.height;

   }

}

public class Main{

  public static void main (String args[]){

     Rectangle square = new Rectangle(45);

     System.out.println(“Area of square: ” + square.getArea());

     

     Rectangle rectangle = new Rectangle(4, 15);

     System.out.println(“Area of rectangle: ” + rectangle.getArea());

  }

}

 

Output:

 

Area of square: 2025

Area of rectangle: 60

 

Explanation: Within the Rectangle class, there exist two constructors: one accepting a sole argument for a square and another accepting distinct arguments for width and height. In the single-argument constructor, ‘this’ is utilised to invoke the other constructor with identical width and height parameters. This strategy circumvents the need for redundant initialisation code for the width and height instance variables.

 

  • Use of “this” Keyword in Java to return the current object from a method

 

Code:

 

class Car {

   private String make;

   private String model;

   public Car(String make, String model) {

       this.make = make;

       this.model = model;

   }

   public Car withMake(String make) {

       this.make = make;

       return this;

   }

   public Car withModel(String model) {

       this.model = model;

       return this;

   }

   public String toString() {

       return this.make + ” ” + this.model;

   }

}

class Main{

  public static void main(String args[]){

     Car car = new Car(“Toyota”, “Camry”);

     car.withMake(“Honda”).withModel(“Accord”);

     System.out.println(car.toString());

  }

}

Output:

 

Honda Accord

 

Explanation: Inside the Car class, there are two methods: withMake() and withModel(), responsible for altering the make and model instance variables, respectively. These methods are designed to return the current object instance, enabling a chaining mechanism for setting multiple properties of the object within a single statement. Utilising ‘this’ to return the current object instance from these methods simplifies the chaining process.

 

  • Use of this Keyword in Java to pass the current object as an argument to another method.

 

Code:

 

class BankAccount {

   private double balance;

   public BankAccount(double balance) {

       this.balance = balance;

   }

   public void deposit(double amount) {

       this.balance += amount;

       System.out.println(“Deposited ” + amount + “, new balance is ” + this.balance);

   }

   public void transfer(BankAccount otherAccount, double amount) {

       this.balance -= amount;

       otherAccount.deposit(amount);

       System.out.println(“Transferred ” + amount + ” from this account to other account”);

   }

}

public class Main{

  public static void main(String args[]){

     BankAccount account1 = new BankAccount(5467);

     BankAccount account2 = new BankAccount(556);

     account1.transfer(account2, 444);

  }

}

 

Output:

 

Deposited 444.0, new balance is 1000.0

Transferred 444.0 from this account to other account

 

Explanation: The transfer() function accepts another BankAccount object and a double amount as parameters, facilitating the transfer of the specified amount from this account to the target account. We employ ‘this’ to indicate the current object instance while invoking the deposit() function on the target account, transmitting the current account’s balance as the deposit amount. Consequently, the deposit amount is appended to the target account’s balance and deducted from the current account’s balance.

 

Also Read: Types of Inheritance in Java

 

Benefits of “this” keyword in Java

 

Here are some advantages of using the “this” keyword in Java:

 

  • Preventing Name Conflicts: Often, constructor parameters may share the name as instance variables within a class. In such cases, the “this” keyword aids programmers in circumventing conflicts between these entities. 


  • Enhancing Readability: The ‘this’ keyword contributes to clearer and more understandable code, especially in scenarios involving intricate class hierarchies.


  • Promoting Code Reusability: Utilising ‘this’ to invoke another constructor within the same class can minimise code repetition and enhance the reusability of code segments.


  • Improving Encapsulation: By employing ‘this’ to reference instance variables rather than local ones, programmers can bolster encapsulation and mitigate the risk of inadvertently modifying incorrect variables.

 

To Cut it Short,

 

In Java, the “this” keyword plays a crucial role in differentiating object instances within a class, aiding in resolving naming conflicts, improving code clarity, and enabling seamless method chaining. Mastering its intricacies can significantly boost one’s Java programming expertise. If you’re willing to explore Java further and excel in full-stack development for web and mobile apps, explore the Certificate Program in Full Stack Development with Specialisation for  Web and Mobile. Seize the opportunity to refine your skills and venture into the dynamic realm of software development.

 

 

FAQs
The 'this' keyword refers to the current object, while 'super' grants access to parent class members. They aid in naming resolution, distinguishing variables, and constructor invocation.
Consider the 'this' keyword in Java as a label, pinpointing the current object in your code. It's pivotal in Java, and grasping its function can greatly enhance your coding expertise.
A frequent use of the 'this' keyword arises when a field is overshadowed by a method or constructor parameter. In constructors, each argument may overshadow one of the object's fields; for instance, within the constructor, 'x' represents a local copy of the constructor's initial argument.

Updated on July 2, 2024

Link

Upskill with expert articles

View all
Free courses curated for you
Basics of Python
Basics of Python
icon
5 Hrs. duration
icon
Beginner level
icon
9 Modules
icon
Certification included
avatar
1800+ Learners
View
Essentials of Excel
Essentials of Excel
icon
4 Hrs. duration
icon
Beginner level
icon
12 Modules
icon
Certification included
avatar
2200+ Learners
View
Basics of SQL
Basics of SQL
icon
12 Hrs. duration
icon
Beginner level
icon
12 Modules
icon
Certification included
avatar
2600+ Learners
View
next_arrow
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved