This Keyword in Java

The this keyword in Java is a reference to the current object — the instance on which a method or constructor is being called. It has several practical uses across Java programs.

Resolving Naming Conflicts

When a constructor or method parameter has the same name as an instance variable, this is used to distinguish the instance variable from the parameter.

class Student {
    String name;
    Student(String name) {
        this.name = name; // this.name refers to the instance variable
    }
}

Calling Another Constructor (Constructor Chaining)

this() can be used inside a constructor to call another constructor of the same class, which is useful for avoiding duplicate initialization code.

class Box {
    int side;
    Box() {
        this(10); // calls the constructor below
    }
    Box(int side) {
        this.side = side;
    }
}

Passing the Current Object

this can be passed as an argument to another method or constructor when that method needs a reference to the calling object.

Returning the Current Object

Methods can return this to enable method chaining, where multiple method calls are linked together in a single statement.

  • this.variable — refers to the current object's field
  • this.method() — calls a method on the current object
  • this() — calls another constructor in the same class
While this is often optional when there's no naming conflict, using it explicitly can make code clearer, especially in constructors and setter methods.

Master Java with Uncodemy

Hands-on training, live projects, and placement support in our Java Programming Course.

Explore the Course