In this lesson, you will learn.
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.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.
// 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.
The ‘this’ keyword can be used in many ways.

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.
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,
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.
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();
}
}
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.
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();
}
}
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.
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;
}
}
You can use this to explicitly call a method of the current class, though it’s often implicit.
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.
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.
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);
}
}
Default Constructor
X=100
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();
}
}
X=100
Default Constructor
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();
}
}
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
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.
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.
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();
}
}
X=100,Y=200
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
}
}
Value: 6
MyValue class wants to be modified by a Modifier object.modify method passes this (the current MyValue instance) to the increment method of the Modifier.Modifier then modifies the MyValue object.
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));
}
}
Are equal: true
MyNumber class wants to compare itself with another MyNumber object using a Comparator.isEqualTo method passes this (the current MyNumber instance) and the other MyNumber instance to the areEqual method of the Comparator.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
}
}
Processed value: 20
processData() calls performCalculation(), passing this (the current DataProcessor object).performCalculation() receives the DataProcessor object and modifies its value.this), allowing multiple method calls to be linked together in a single line of code.
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
}
}
Value: 6
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();
}
}
Result: HELLO JAVA
StringProcessor class provides methods for manipulating a string, and each method returns this.
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.
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.
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);
}
}
Window created.
Button registered with the window.
Button created and registered.
Wide range of courses available on this platform , the lectures are well organised and structured which makes it easy to understand the concepts
very helpful course as it helped me to strengthen my concepts
You must be logged in to submit a review.