Course topics

By WebNest Studio Engineering Team

Java - Core Tutorial

this Keyword

this is a reference variable in Java that refers to the current object — the specific object on which an instance method or constructor is currently executing. It is implicitly available inside every non-static method and constructor, even though you never declare or assign it yourself.

Why it matters

Constructors and setters usually name their parameters after the fields they set, and without this the assignment quietly does nothing: the parameter is assigned to itself and the field keeps its default. That bug compiles cleanly and shows up later as a null or a zero, which makes it worth understanding exactly what this refers to.

Watch: How Java's this Keyword Resolves Shadowing

A quick look at how this tells a field apart from a parameter with the same name, and what goes wrong when it is left out.

Watch on YouTube

this.field — Resolving Naming Conflicts

The most common use of this is to distinguish an instance variable from a parameter or local variable that shares the same name, a situation called shadowing. Writing this.balance = balance; inside a constructor tells the compiler that the left-hand balance is the object's field, while the plain balance on the right is the constructor's parameter. Without the this. prefix in that scenario, balance = balance; would simply assign the parameter to itself and leave the field untouched.

this(...) — Constructor Chaining

When used as a method-call-like expression, this(...) invokes another constructor of the same class, matched by argument list, as covered in the constructors topic. This is a completely different use from this.field: this(...) can only appear inside a constructor, at most once, while this.field can appear anywhere inside an instance method or constructor. Until Java 24 the this(...) call had to be the first statement; since Java 25 it may follow statements that don't use the object being built, such as argument checks.

Other Uses of this

this can also be passed as an argument to another method (for example, registering the current object as a listener), returned from a method to support method chaining (return this;), and used to explicitly call another instance method of the current object (this.someMethod()), although that explicit form is usually optional since the method name alone resolves to the current object by default.

  • this.field — refers to the current object's field, most often to resolve shadowing.
  • this(...) — calls another constructor in the same class; code before it must not use the object being built.
  • this is never available inside a static context, because static code has no current object.

How Java Resolves a Name: Why Shadowing Happens

When Java sees a plain name like balance, it looks in the closest scope first: local variables and parameters, then the fields of the current class, then inherited fields. So inside a constructor with a parameter called balance, the plain name always means the parameter, and the field is hidden (shadowed). this.balance skips the local scope and goes straight to the current object's field. When there is no clash, for example a field balance and a parameter amount, writing balance already means the field, so this. is optional.

Why the Bug Is Silent

owner = owner; is perfectly legal Java: it assigns the parameter to itself. The compiler doesn't reject it, the program runs, and the field simply keeps its default value (null, 0 or false). You only notice later, when something reads the field. Two habits prevent it: always write this.field = field when the names match, and make fields final where you can. The compiler then reports a final field the constructor forgot to assign.

Outer.this in Inner Classes

Inside an inner (non-static nested) class, this means the inner object. To reach the enclosing object, write the outer class name followed by .this, as in Course.this.title. This is the only way to read an outer field that the inner class has shadowed with a field of the same name. Static nested classes have no enclosing object, so Outer.this is not available there.

Passing this Safely

Handing this to another object (as an argument or a callback) is normal in methods. Avoid doing it inside a constructor, though: the other object then holds a reference to an object that isn't fully initialised yet, which can expose half-set fields. Finish construction first, then register the object from a method or a factory.

Examples

Resolving shadowed parameters with this.field

Java
public class Employee {
    String name;
    double salary;

    Employee(String name, double salary) {
        this.name = name;     // this.name is the field, name is the parameter
        this.salary = salary;
    }

    Employee giveRaise(double amount) {
        this.salary += amount;
        return this; // enables method chaining
    }

    public static void main(String[] args) {
        Employee emp = new Employee("Dev", 50000.0);
        emp.giveRaise(2000.0).giveRaise(1500.0);
        System.out.println(emp.name + " now earns " + emp.salary);
    }
}
Output
Dev now earns 53500.0

The silent shadowing bug: a field left at its default value

Java
class Account {
    String owner;
    double balance;

    Account(String owner, double balance) {
        owner = owner;          // bug: assigns the parameter to itself
        this.balance = balance; // correct: assigns the parameter to the field
    }
}

public class ShadowingBug {
    public static void main(String[] args) {
        Account acc = new Account("Meera", 2500.0);
        System.out.println("Owner: " + acc.owner);
        System.out.println("Balance: " + acc.balance);
    }
}
Output
Owner: null
Balance: 2500.0

A local variable, this.field and Outer.this.field with the same name

Java
class Course {
    String title = "Core Java";

    class Lesson {
        String title = "this Keyword";

        void describe() {
            String title = "local variable";
            System.out.println(title);              // the local variable
            System.out.println(this.title);         // the Lesson object's field
            System.out.println(Course.this.title);  // the enclosing Course object's field
        }
    }
}

public class OuterThisDemo {
    public static void main(String[] args) {
        Course course = new Course();
        Course.Lesson lesson = course.new Lesson();
        lesson.describe();
    }
}
Output
local variable
this Keyword
Core Java

Passing this from a method so another object can keep a reference

Java
import java.util.ArrayList;
import java.util.List;

class Classroom {
    private final List<Student> students = new ArrayList<>();

    void enrol(Student student) {
        students.add(student);
    }

    int size() {
        return students.size();
    }
}

class Student {
    final String name;

    Student(String name) {
        this.name = name;
    }

    void join(Classroom room) {
        room.enrol(this); // hand this object to another object
    }
}

public class PassThisDemo {
    public static void main(String[] args) {
        Classroom room = new Classroom();
        new Student("Asha").join(room);
        new Student("Ravi").join(room);
        System.out.println("Students enrolled: " + room.size());
    }
}
Output
Students enrolled: 2

Common Mistakes

  • Forgetting "this." when a constructor parameter shadows an instance field, causing the field to silently stay at its default value.
  • Trying to use "this" inside a static method, which does not compile since static code has no current object.
  • Using the object (this, its fields or instance methods) before the this(...) call in a constructor.
  • Confusing this(...) (same-class constructor chaining) with super(...) (parent-class constructor call).
  • Passing "this" to other objects from inside a constructor, exposing an object that is not fully initialised yet.

Exercise

This program prints null because the constructor assigns the parameter to itself instead of to the field. Fix the constructor so it prints Asha.

Java · starter code
class Employee {
    String name;

    Employee(String name) {
        name = name;
    }
}

public class EmployeeDemo {
    public static void main(String[] args) {
        Employee employee = new Employee("Asha");
        System.out.println(employee.name);
    }
}
Show hints
  • Inside the constructor, the name name refers to the parameter, which hides the field.
  • this.name always refers to the field of the current object.
Show solution
Java · solution
class Employee {
    String name;

    Employee(String name) {
        this.name = name;
    }
}

public class EmployeeDemo {
    public static void main(String[] args) {
        Employee employee = new Employee("Asha");
        System.out.println(employee.name); // Asha
    }
}

Quick quiz

1. What does this refer to inside an instance method?

  • A. The class itself
  • B. The most recently created object
  • C. The superclass object
  • D. The object the method was called on
Show answer

D. this is a reference to the current object: the one whose method or constructor is running.

2. What happens if you use this inside a static method?

  • A. It does not compile
  • B. It is null
  • C. It refers to the class
  • D. It refers to the first object created
Show answer

A. A static method is not called on an object, so there is no current object for this to refer to.

3. What does a method that ends with return this; make possible?

  • A. Recursion
  • B. Method chaining, as in a.setX(1).setY(2)
  • C. Overloading
  • D. Garbage collection
Show answer

B. Returning the current object lets the caller invoke another method on the result immediately, which is how builder-style APIs work.

Interview questions

What are the uses of the this keyword?

Show answer

To refer to a field when a parameter or local variable has the same name. To call another constructor of the same class with this(...). To pass the current object as an argument to another method. And to return the current object from a method, which enables method chaining.

What is the difference between this and super?

Show answer

this refers to the current object and gives access to its own members and constructors. super refers to the superclass part of the current object: it calls a superclass constructor with super(...) and reaches superclass methods or fields that the subclass has overridden or hidden. Neither can be used in a static context.

Key Points to Remember

  • "this" refers to the current object inside instance methods and constructors.
  • "this.field" resolves naming conflicts between fields and parameters/local variables (shadowing).
  • A plain name resolves to the nearest scope first, so "this." is only required when a local name hides the field.
  • "this(...)" chains to another constructor in the same class; code before it must not touch the object being built.
  • "Outer.this" reaches the enclosing object from inside an inner class.
  • "this" cannot be used in a static context, since static members have no associated object.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering