Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Understanding the ‘this’ keyword in Java

In this lesson, you will learn.

  • This Keyword in Java
  • Usage of this keyword
  • Examples

 

What is a ‘this’ Keyword

  1. In Java, this is a reference variable that refers to the current object of a class. It’s a way for an object to refer to itself.
  2. It is used within an instance method or a constructor to refer to the current object on which the method or constructor is invoked.

Note: The this keyword is useful in situations where method parameters have the same name as an instance variable (field) of the current object, allowing the instance variable to be distinguished from the method parameter or local variable.

Example

// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
       this.width = width;
       this.height = height;
       this.depth = depth;
}

Here this.width, this.height, this.depth are the instance variables. The ‘this’ keyword distinguishes the instance variable from local variables.

 

Different Uses of ‘this’ keyword in Java

The ‘this’ keyword can be used in many ways.

thiskeywordusage1

 

1. Referring to the Current Class Instance Variables

  • The this keyword is useful where a method parameter has the same name as an instance variable (field) within a method of a constructor, in such cases, the local variables hide the instance variables.
  • This situation leads to the ambiguity between instance variables and local variables.
  • So, the ‘this’ keyword is used to differentiate the instance and local variables.

Example

class Rectangle
{
     double length, width;//Instance Variables
     Rectangle(double length, double width)
     {
          this.length = length;
          this.width = width;
     }
}

Here, this.length refers to the instance variables.

To better understand ‘this’ keyword, let’s understand the concept of Instance Variable Hiding,

 

Instance Variable Hiding

The example below shows that the local and instance variables are the same. In that case, the local variable hides the instance variables.

 

Let’s understand the problem without using the ‘this’ keyword.

 

Example 1: Instance Variable Hiding (Without ‘this’)

package ch7.l9;

class Point{
	int x,y; //Instance Variables
	
	void getInput(int x, int y) 
	{
		x = x;
		y = y;
	}
	void show() {
        System.out.println("X="+x+",Y="+y);
    }
}
public class ThisExample {
	public static void main(String[] args) {
		Point p1=new Point();
        p1.getInput(5, 6);
        p1.show();
	}
}

Output

X=0,Y=0

However, when a local variable has the same name as an instance variable, the local variable hides the instance variable.

Here is the solution to the above problem.

 

Example 2: Using the ‘this’ Keyword

package ch7.l9;

class Point{
	int x,y; //Instance Variables
	
	void getInput(int x, int y) 
	{
		this.x = x;
		this.y = y;
	}
	void show() {
        System.out.println("X="+x+",Y="+y);
    }
}
public class ThisExample {
	public static void main(String[] args) {
		Point p1=new Point();
        p1.getInput(5, 6);
        p1.show();
	}
}

Output

X=5,Y=6

The ‘this’ lets you refer directly to the object, you can use it to resolve any namespace collisions that might occur between instance variables and local variables.

Hence, to distinguish between these variables, I have used this keyword to output the local variables.

 

Important Note!

The following code snippet shows where ‘this’ is not required because the instance and local variables are different.

class Point{
	int x,y; //Instance Variables
	
	void getInput(int x1, int y1) 
	{
		x = x1;
		y = y1;
	}
}

 

2. Invoking the Current Class Method

You can use this to explicitly call a method of the current class, though it’s often implicit.

Syntax

this.method-name();

 

 

If you do not use ‘this’ then the compiler automatically uses the ‘this’ keyword to call the method of the current class as shown in the below figure.

In show(), this.display() and display() both call the display() method of the same object. While this is technically unnecessary in this case, it can sometimes improve readability.

 

3. Invoking the Current Class Constructor(Constructor Chaining)

this() can be used to call another constructor of the same class from within a constructor. This is called constructor chaining and must be the first statement in the constructor.

 

 

It can be used to invoke another constructor of the current class in terms of constructor chaining.

 

Example-1: Calling Default Constructor From Parameterized Constructor

package ch7.l9;

class ClassA{
	
	public ClassA() {
		System.out.println("Default Constructor");
	}
	public ClassA(int x){
		this();//Calls default constructor
		System.out.println("X="+x);
	}
}
public class ThisExample3 {

	public static void main(String[] args) {
		ClassA objA=new ClassA(100);
	}
}

Output

Default Constructor
X=100

 

Example 2: Calling Parameterized Constructor From Default Constructor

package ch7.l9;

class ClassA{
	
	public ClassA() {
		this(100);
		System.out.println("Default Constructor");
	}
	public ClassA(int x){
		System.out.println("X="+x);
	}
}
public class ThisExample3 {

	public static void main(String[] args) {
		ClassA objA=new ClassA();
	}
}

Output

X=100
Default Constructor

 

Example 3: Constructor Chaining

package ch7.l9;

class Employee {
    private String name;
    private int age;
    private double salary;

    // Constructor with all parameters
    public Employee(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    // Constructor with two parameters, 
    // chaining this to the main constructor
    public Employee(String name, int age) {
        this(name, age, 0.0); // Assuming default salary is 0.0
    }

    // Default constructor, chaining this 
    // to another constructor with default values
    public Employee() {
        this("Unknown", 0); // Default name and age
    }

    // Method to display employee information
    public void displayInfo() {
        System.out.println("Employee Name: "+name+", "
        		+ "Age: "+age+ ",Salary: $"+salary);
    }
}

public class EmployeeMain {
	public static void main(String[] args) {
        Employee emp1 = new Employee("John Doe", 30, 50000.0);
        Employee emp2 = new Employee("Jane Doe", 25);
        Employee emp3 = new Employee();
        
        // Displays: Employee Name: John Doe, Age: 30, Salary: $50000.0
        emp1.displayInfo(); 
        // Displays: Employee Name: Jane Doe, Age: 25, Salary: $0.0
        emp2.displayInfo();
        // Displays: Employee Name: Unknown, Age: 0, Salary: $0.0
        emp3.displayInfo();
    }
}

Output

Employee Name: John Doe, Age: 30,Salary: $50000.0
Employee Name: Jane Doe, Age: 25,Salary: $0.0
Employee Name: Unknown, Age: 0,Salary: $0.0

 

Important Note!

When using this for constructor chaining within the same class, it must be the first statement in the constructor, and you cannot call more than one constructor directly since it would lead to a compile-time error.

 

4. Using ‘this’ to Pass as an Argument in the Method

In Java, the this keyword can be used to pass the current object as an argument to another method.

Note: It is useful when you need to provide a reference to the current object to another object’s method for various purposes, such as callback mechanism, event handling, or initiating interactions between different objects within a system.

 

Example 1: Pass the Current Object as an Argument to a Method

package ch7.l9;

class Demo{
	int x,y;
	//Constructor
	public Demo() {
		x=100;
		y=200;
	}
	//Method receives the 'this' as an argument
	void display(Demo obj1) {
		System.out.println("X="+obj1.x+",Y="+obj1.y);
	}
	
	void show() {
		display(this);
	}
}
public class ThisExample4 {

	public static void main(String[] args) {
		Demo obj=new Demo();
		obj.show();
	}
}

Output

X=100,Y=200

 

Example-2: Object Modification by Another Object

class Modifier {
    void increment(MyValue value) {
        value.setValue(value.getValue() + 1);
    }
}

class MyValue {
    private int value;

    MyValue(int value) {
        this.value = value;
    }

    int getValue() {
        return value;
    }

    void setValue(int value) {
        this.value = value;
    }

    void modify(Modifier modifier) {
        modifier.increment(this); // Passing 'this'
    }
}

public class ModificationExample {
    public static void main(String[] args) {
        MyValue val = new MyValue(5);
        Modifier mod = new Modifier();
        val.modify(mod);
        System.out.println("Value: " + val.getValue()); // Output: Value: 6
    }
}


Output:

Value: 6

Explanation:

  • The MyValue class wants to be modified by a Modifier object.
  • The modify method passes this (the current MyValue instance) to the increment method of the Modifier.
  • The Modifier then modifies the MyValue object.

 

Example-3: Object Comparision

class Comparator {
    boolean areEqual(MyNumber num1, MyNumber num2) {
        return num1.getValue() == num2.getValue();
    }
}

class MyNumber {
    private int value;

    MyNumber(int value) {
        this.value = value;
    }

    int getValue() {
        return value;
    }

    boolean isEqualTo(Comparator comparator, MyNumber other) {
        return comparator.areEqual(this, other); // Passing 'this'
    }
}

public class ComparisonExample {
    public static void main(String[] args) {
        MyNumber num1 = new MyNumber(10);
        MyNumber num2 = new MyNumber(10);
        Comparator comp = new Comparator();
        System.out.println("Are equal: " + num1.isEqualTo(comp, num2));
    }
}

Output:

Are equal: true

Explanation:

  • The MyNumber class wants to compare itself with another MyNumber object using a Comparator.
  • The isEqualTo method passes this (the current MyNumber instance) and the other MyNumber instance to the areEqual method of the Comparator.
  • The comparator then compares the two numbers.

 

Example-4: Passing this to a Helper Method within the Same Class

class DataProcessor {
    private int value;

    DataProcessor(int value) {
        this.value = value;
    }

    void processData() {
        performCalculation(this); // Passing 'this' to a helper method
        displayResult();
    }

    private void performCalculation(DataProcessor dp) {
        dp.value *= 2; // Modify the object's value
    }

    private void displayResult() {
        System.out.println("Processed value: " + value);
    }

    public static void main(String[] args) {
        DataProcessor processor = new DataProcessor(10);
        processor.processData(); // Output: Processed value: 20
    }
}


Output:

Processed value: 20


Explanation:

  • processData() calls performCalculation(), passing this (the current DataProcessor object).
  • performCalculation() receives the DataProcessor object and modifies its value.
  • This is useful for breaking down complex logic into smaller, manageable methods while still working on the same object.

 

5. Using ‘this’ to return the Current Class Instance

  1. The ‘this’ keyword can be used to return the current class instance that can be further used to call another method and so on.
  2. It is specially used in Java, for implementing method chaining.
  3. Method chaining is a design pattern where methods return the current object (this), allowing multiple method calls to be linked together in a single line of code.

Example 1: Using ‘this’ to return the Current Class Instance(Method Chaining)

package thisuse;
 
class Calculator {
    int value;
 
    Calculator setValue(int value) {
        this.value = value;
        return this; // Returns the current object
    }
 
    Calculator add(int num) {
        this.value += num;
        return this;
    }
 
    Calculator subtract(int num) {
        this.value -= num;
        return this;
    }
     
    Calculator mul(int num) {
        this.value *= num;
        return this;
    }
     
    Calculator divide(int num) {
        this.value /= num;
        return this;
    }
 
    void display() {
        System.out.println("Value: " + value);
    }
 
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        calc.setValue(10).add(2).subtract(3).mul(6).divide(9).display(); // Method chaining
    }
}


Output:

Value: 6


 

Example 2: String Manipulation

class StringProcessor {
    private String text = "";

    StringProcessor append(String str) {
        this.text += str;
        return this;
    }

    StringProcessor toUpperCase() {
        this.text = this.text.toUpperCase();
        return this;
    }

    StringProcessor replace(String oldStr, String newStr) {
        this.text = this.text.replace(oldStr, newStr);
        return this;
    }

    void display() {
        System.out.println("Result: " + text);
    }

    public static void main(String[] args) {
        StringProcessor processor = new StringProcessor();
        processor.append("hello ").append("world").toUpperCase().replace("WORLD", "JAVA").display();
    }
}


Output

Result: HELLO JAVA


Explanation:

  • The StringProcessor class provides methods for manipulating a string, and each method returns this.
  • This allows us to chain multiple string operations together.
  • The output would be: Result: HELLO JAVA.

 

6. Using ‘this’ to Pass an Argument to a Constructor Call

The this keyword as an argument in a constructor call allows you to pass the current instance of a class as an argument to another constructor, either within the same class or in a different class.

Note!

This can be particularly useful for setting up relationships between objects at the time of their creation, such as establishing parent-child relationships, registering listeners, or initializing components that need a reference back to the creating object.

 

Example 1: Using ‘this’ to Pass an Argument to a Constructor Call

package thisuse;

class Window {
    public Window() {
        System.out.println("Window created.");
    }
 
    // Method to register a Button with this Window
    public void registerButton(Button button) {
        System.out.println("Button registered with the window.");
        // Additional logic to add the button to 
        // the window's list of buttons could be added here
    }
}
 
class Button {
    // Constructor takes a Window object and 
    // registers this Button with it
    public Button(Window window) {
        window.registerButton(this); // Passes itself to the Window
        System.out.println("Button created and registered.");
    }
}
 
public class ThisExample6 {
 
    public static void main(String[] args) {
        Window window = new Window();
        // Button registers itself with the Window during creation
        Button button = new Button(window); 
    }
}


Output:

Window created.
Button registered with the window.
Button created and registered.

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

5.0
5.0 out of 5 stars (based on 2 reviews)
Excellent100%
Very good0%
Average0%
Poor0%
Terrible0%

 

 

05/04/2025

Wide range of courses available on this platform , the lectures are well organised and structured which makes it easy to understand the concepts

05/04/2025

very helpful course as it helped me to strengthen my concepts

 

 

Submit a Review