Popular
Data Science
Technology
Finance
Management
Future Tech
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.
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.
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.
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.
Here are some of the basic uses of “this” keyword in Java:
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.
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.
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.
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
Here are some advantages of using the “this” keyword in Java:
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.
The DevOps Playbook
Simplify deployment with Docker containers.
Streamline development with modern practices.
Enhance efficiency with automated workflows.
Popular
Data Science
Technology
Finance
Management
Future Tech
Accelerator Program in Business Analytics & Data Science
Integrated Program in Data Science, AI and ML
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
Integrated Program in Finance and Financial Technologies
Certificate Program in Financial Analysis, Valuation and Risk Management
© 2024 Hero Vired. All rights reserved