OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 10 : this Keyword in Java

 

Unit - 2
Topic - 10 : this Keyword in Java

In Java, sometimes a method needs to refer to the object that invoked it.
To enable this, Java provides the this keyword.


What is this?

  • this is a reference to the current object (the object whose method or constructor is being executed).

  • You can use this anywhere a reference to the current object is needed.

  • It’s implicitly passed to instance methods and constructors.


1. Simple Use of this in a Constructor

Even if you don't explicitly use this, Java automatically applies it when accessing instance variables.
Example:

class Box { double width, height, depth; // Constructor using this keyword Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; } void display() { System.out.println("Width: " + width + ", Height: " + height + ", Depth: " + depth); } } public class ThisExample { public static void main(String[] args) { Box mybox = new Box(10, 20, 30); mybox.display(); } }

Output:

Width: 10.0, Height: 20.0, Depth: 30.0

💡 Explanation:
Here, this.width refers to the instance variable, and w is the constructor parameter. Without this, the assignment would be ambiguous when parameter names match instance variable names.


2. Instance Variable Hiding

When local variables or method parameters have the same name as instance variables, they hide the instance variables.
In such cases, this is used to refer to the instance variable.

class Employee { String name; int age; Employee(String name, int age) { // Resolving name conflict using this this.name = name; this.age = age; } void show() { System.out.println("Name: " + name + ", Age: " + age); } } public class ThisVariableHiding { public static void main(String[] args) { Employee e = new Employee("John", 25); e.show(); } }

Output:

Name: John, Age: 25

💡 Explanation:
Without this, name = name; would assign the parameter to itself, leaving the instance variable uninitialized.


3. Other Uses of this

  • Calling another constructor in the same class:
    this(arguments)

  • Passing the current object as a parameter to another method:
    someMethod(this);

  • Returning the current object from a method for method chaining.


Key Points

  • this always refers to the current object.

  • Avoid variable name conflicts when possible, but use this when necessary.

  • Helpful for constructor chaining, method chaining, and passing current object.

Comments

Popular posts from this blog

Career Guide - B.Tech Students

Artificial Intelligence - UNIT - 1 Topic - 1 : Introduction to AI (Artificial Intelligence)

Financial Aid for Students: Scholarships from Government, NGOs & Companies