Hero Vired Logo
Programs
BlogsReviews

More

Vired Library

Complimentary 4-week Gen AI Course with Select Programs.

Request a callback

or Chat with us on

Home
Blogs
A Detailed Exploration of the “this” Keyword in Java

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.

 

Table of Contents:

 

 

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.

 

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.

 

 

FAQ's

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.

High-growth programs

Choose the relevant program for yourself and kickstart your career

You may also like

Carefully gathered content to add value to and expand your knowledge horizons

Hero Vired logo
Hero Vired is a premium LearnTech company offering industry-relevant programs in partnership with world-class institutions to create the change-makers of tomorrow. Part of the rich legacy of the Hero Group, we aim to transform the skilling landscape in India by creating programs delivered by leading industry practitioners that help professionals and students enhance their skills and employability.

Data Science

Accelerator Program in Business Analytics & Data Science

Integrated Program in Data Science, AI and ML

Accelerator Program in AI and Machine Learning

Advanced Certification Program in Data Science & Analytics

Technology

Certificate Program in Full Stack Development with Specialization for Web and Mobile

Certificate Program in DevOps and Cloud Engineering

Certificate Program in Application Development

Certificate Program in Cybersecurity Essentials & Risk Assessment

Finance

Integrated Program in Finance and Financial Technologies

Certificate Program in Financial Analysis, Valuation and Risk Management

Management

Certificate Program in Strategic Management and Business Essentials

Executive Program in Product Management

Certificate Program in Product Management

Certificate Program in Technology-enabled Sales

Future Tech

Certificate Program in Gaming & Esports

Certificate Program in Extended Reality (VR+AR)

Professional Diploma in UX Design

Blogs
Reviews
In the News
About Us
Contact us
Vired Library
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

© 2024 Hero Vired. All rights reserved