The this keyword
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Inside a constructor or an instance method, this means the current object: the object being created, or the object the method was called on. this.name means "this object's name field".
The same-name problem
Shadowing happens when a parameter or local variable has the same name as a field. Inside that method or constructor, the plain name means the parameter, and the field is hidden.
It feels natural to write Student(String name, int marks). But inside it, plain name now means the parameter: a parameter with a field's name shadows (hides) the field, so name = name; copies the parameter into itself.
Example 1 · name = name changes nothing
class Student { String name; int marks;
Student(String name, int marks) { name = name; marks = marks; }}
public class ShadowDemo { public static void main(String[] args) { Student s = new Student("Kavya", 88); System.out.println(s.name + " " + s.marks); }}null 0
What this code does
- Inside the constructor,
nameandmarksmean the parameters, so each line copies a parameter into itself. - The fields are never set and keep their default values,
nulland0.
javac gives no error and no warning (some editors underline the line). Java always picks the closest name: first local variables and parameters, then fields.
this.name means the field
this is a reference to the current object: the object being created by a constructor, or the object an instance method was called on. this.name means the current object's name field.
Write this.name = name;. On the left, this.name is the field of the object being built; on the right, name is the parameter. This is the usual way to write constructors in Java.
Example 2 · Fixing it with this
class Student { String name; int marks;
Student(String name, int marks) { this.name = name; this.marks = marks; }}
public class ThisDemo { public static void main(String[] args) { Student s = new Student("Kavya", 88); System.out.println(s.name + " " + s.marks); }}Kavya 88
What this code does
this.nameis the field of the new object;namealone is the parameter.- Only
this.was added, and the fields are now set correctly.
The same rule works in methods: in void addRuns(int runs), this.runs is the field and plain runs is the parameter.
this is the current object
One show() method serves every batsman, so how does it know whose runs to print? Java passes the object before the dot: inside the method it is called this, just as in a constructor it is the object being built.
Example 3 · this changes with the object
class Batsman { String name; int runs;
Batsman(String name) { this.name = name; }
void addRuns(int runs) { this.runs = this.runs + runs; this.show(); }
void show() { System.out.println(name + ": " + runs); }}
public class BatsmanDemo { public static void main(String[] args) { Batsman b1 = new Batsman("Rohit"); Batsman b2 = new Batsman("Virat"); b1.addRuns(4); b2.addRuns(6); b1.addRuns(6); }}Rohit: 4 Virat: 6 Rohit: 10
What this code does
- In
b1.addRuns(4),thisis Rohit; inb2.addRuns(6), it is Virat. One method serves both objects. this.show()callsshowon the same batsman. Inshow, nothing hides the fields, so plainnameandrunswork.
Example 4 · this and another object
class Student { String name; int marks;
Student(String name, int marks) { this.name = name; this.marks = marks; }
void compareWith(Student other) { if (this.marks > other.marks) { System.out.println(this.name + " scored more than " + other.name); } else { System.out.println(this.name + " did not score more than " + other.name); } }}
public class CompareDemo { public static void main(String[] args) { Student kavya = new Student("Kavya", 92); Student rohan = new Student("Rohan", 85); kavya.compareWith(rohan); rohan.compareWith(kavya); }}Kavya scored more than Rohan Rohan did not score more than Kavya
What this code does
thisis the object before the dot;otheris the object passed in the brackets.- Swapping them,
rohan.compareWith(kavya), swaps which object isthis.
A method can use two objects at once: this, the one before the dot, and a parameter such as other. It is the same method-on-an-object idea as in State and behaviour (opens in a new tab), now with a name for "my own object".
Passing this and returning this
A student joins a club and hands itself to the team with t.add(this). this is an ordinary reference, so it can be passed to a method, stored in an array, or returned with return this;.
Example 5 · Passing this to another object
class Team { String name; Student[] members = new Student[3]; int count;
Team(String name) { this.name = name; }
void add(Student s) { members[count] = s; count = count + 1; }}
class Student { String name;
Student(String name) { this.name = name; }
void join(Team t) { t.add(this); System.out.println(name + " joined " + t.name + ", members: " + t.count); }}
public class TeamDemo { public static void main(String[] args) { Team quiz = new Team("Quiz Club"); new Student("Diya").join(quiz); new Student("Arjun").join(quiz); System.out.println("First member: " + quiz.members[0].name); }}Diya joined Quiz Club, members: 1 Arjun joined Quiz Club, members: 2 First member: Diya
What this code does
- Inside
join,thisis the student who is joining.t.add(this)hands that very object to the team. - The team stores the reference in its array, so
quiz.members[0]is the Diya object itself, not a copy.
Example 6 · Returning this for chaining
class Order { String customer; int items; int total;
Order(String customer) { this.customer = customer; }
Order addItem(String item, int price) { this.items = this.items + 1; this.total = this.total + price; System.out.println("Added " + item); return this; }
void show() { System.out.println(customer + ": " + items + " items, Rs. " + total); }}
public class ChainDemo { public static void main(String[] args) { Order o = new Order("Aarav"); o.addItem("Dosa", 80).addItem("Coffee", 40).addItem("Vada", 50); o.show(); }}Added Dosa Added Coffee Added Vada Aarav: 3 items, Rs. 170
What this code does
addItemreturnsthis, the sameOrder, so its return type isOrder.- Each call in the chain works on the object the previous call returned, which is always
o.
A method that returns this has the class as its return type, like Order addItem(...), so the next call can follow at once: o.addItem(...).addItem(...). This is method chaining; use it only where the chain reads naturally.
When you need this, and where you cannot use it
Use this when a parameter or local variable has the same name as a field; otherwise marks and this.marks mean the same. main is static and belongs to no object, so it has no this at all.
Each snippet below has one wrong line. Tap it, then check the fix.
Find the bug
Find the this mistake
Select the line that is wrong.
This should give every new bus 40 seats.
Round 1 of 4Next step
Check your understanding
12 quick questions