Java OOP
this Keyword
Complete lesson for this Keyword using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — this Keyword
Section: Java OOP. The Java this keyword — a reference to the current object. Six uses with real-life examples, where this cannot be used, this vs super, this vs this(), inner classes, lambdas, and the escaping-this pitfall.
What is the this keyword?
thisis a reference variable that points to the current object: the object whose method or constructor is running right now.- It is created automatically. You never declare it, and you cannot assign a new value to it (
this = otheris a compile error). - It exists only inside instance methods, constructors, and instance initializer blocks, because only they run "on" an object.
- Real-life example: when Asha says "my roll number", "my" means Asha. When Ravi says the same sentence, "my" means Ravi.
thisis the word "my" for an object.
public class Student {
String name;
Student(String name) {
this.name = name;
}
void introduce() {
System.out.println("My name is " + this.name); // this = the object that called introduce()
}
public static void main(String[] args) {
Student asha = new Student("Asha");
Student ravi = new Student("Ravi");
asha.introduce(); // My name is Asha (this == asha)
ravi.introduce(); // My name is Ravi (this == ravi)
}
} How this works behind the scenes
- When you call
asha.introduce(), the compiler quietly passesashaas a hidden first argument. Inside the method, that hidden argument is calledthis. - So
thisand the calling reference point to the same object:this == ashais true inside that call. - Static methods are called on the class, not an object, so they receive no hidden argument and have no
this.
// What you write:
asha.introduce();
// What the JVM effectively does:
Student.introduce(asha); // asha becomes "this" inside the method
// Proof: this and the reference are the same object
class Check {
void whoAmI(Check ref) {
System.out.println(this == ref); // true when called as c.whoAmI(c)
}
} Six uses of the this keyword
| Use | Syntax | Purpose | Small real-life example |
|---|---|---|---|
| 1. Refer to the current object field | this.name = name; | Resolve name clash between field and parameter | Two people named Ravi in a room: "this Ravi" points to one |
| 2. Call a current class method | this.calculate(); | Call another instance method of the same object | A chef saying "I will also make the sauce" |
| 3. Call a current class constructor | this("guest", 0); | Constructor chaining, reuse code | Default ticket booking that fills in "Sleeper" for you |
| 4. Pass as a method argument | bank.register(this); | Hand the current object to another method | Showing your own ID card at the counter |
| 5. Pass as a constructor argument | new Invoice(this); | Link a new object back to the current one | An order creating its own bill with its own details |
| 6. Return the current object | return this; | Method chaining / fluent API | Burger counter: add cheese, add fries, done |
Use 1: this.field to resolve shadowing
- When a parameter or local variable has the same name as a field, the local name "shadows" (hides) the field inside that method.
name = name;then assigns the parameter to itself. The field never changes and staysnullor0. The compiler does not complain.this.namealways means the field of the current object, sothis.name = name;copies the parameter into the field.- Real-life example: a teacher with two students named Ravi says "Ravi, sit down" and nobody knows who. Saying "this Ravi" while pointing removes the confusion.
class WithoutThis {
String name;
int age;
WithoutThis(String name, int age) {
name = name; // parameter = parameter (field untouched)
age = age;
}
}
class WithThis {
String name;
int age;
WithThis(String name, int age) {
this.name = name; // field = parameter
this.age = age;
}
}
public class ShadowDemo {
public static void main(String[] args) {
WithoutThis a = new WithoutThis("Asha", 15);
WithThis b = new WithThis("Asha", 15);
System.out.println(a.name + " " + a.age); // null 0 (bug)
System.out.println(b.name + " " + b.age); // Asha 15 (correct)
}
} Use 2: calling another method of the current object
- Inside an instance method,
calculateTax()andthis.calculateTax()mean the same thing; the compiler addsthis.for you. - Writing
this.explicitly can make it obvious that you are calling an instance method, not a static helper. - Real-life example: a restaurant bill. "Generate bill" first asks the same bill to compute tax, then its own total.
public class Bill {
double amount;
Bill(double amount) { this.amount = amount; }
double tax() { return amount * 0.05; }
double total() {
return this.amount + this.tax(); // same as amount + tax()
}
void print() {
System.out.println("Amount " + amount + ", tax " + this.tax() + ", total " + this.total());
}
public static void main(String[] args) {
new Bill(800).print(); // Amount 800.0, tax 40.0, total 840.0
}
} Use 3: this() to call another constructor
this(...)calls another constructor of the same class. It must be the first statement of the constructor.- It keeps all field assignments in one constructor and lets shorter constructors supply default values.
- Real-life example: buying a movie ticket without choosing a seat type gives you "Regular"; choosing gives you what you asked for. Both go through the same ticket printer.
public class MovieTicket {
String movie;
String seatType;
int price;
MovieTicket(String movie) {
this(movie, "Regular"); // chain
}
MovieTicket(String movie, String seatType) {
this.movie = movie;
this.seatType = seatType;
this.price = seatType.equals("Recliner") ? 450 : 200;
}
public static void main(String[] args) {
MovieTicket t1 = new MovieTicket("Interstellar");
MovieTicket t2 = new MovieTicket("Interstellar", "Recliner");
System.out.println(t1.seatType + " " + t1.price); // Regular 200
System.out.println(t2.seatType + " " + t2.price); // Recliner 450
}
} Use 4: passing this as a method argument
- An object can hand itself to another object or method by passing
this. - Common in event listeners (
button.addActionListener(this)), registries, and callbacks. - Real-life example: at a hospital reception, a patient hands over their own ID card so the receptionist can register them.
import java.util.ArrayList;
import java.util.List;
class Reception {
private final List<Patient> registered = new ArrayList<>();
void register(Patient p) {
registered.add(p);
System.out.println("Registered " + p.name + " (total " + registered.size() + ")");
}
}
class Patient {
String name;
Patient(String name) { this.name = name; }
void checkIn(Reception desk) {
desk.register(this); // "here is me"
}
}
public class HospitalDemo {
public static void main(String[] args) {
Reception desk = new Reception();
new Patient("Meena").checkIn(desk); // Registered Meena (total 1)
new Patient("Kiran").checkIn(desk); // Registered Kiran (total 2)
}
} Use 5: passing this to a constructor
- A new object can receive a reference to the object that created it, so the two stay linked.
- Typical in parent-child structures: an
Ordercreates itsInvoice, aCarcreates itsEngine, aDepartmentcreates itsEmployee. - Real-life example: an online order generates its own invoice. The invoice reads the customer and amount straight from that order.
class Invoice {
private final Order order;
Invoice(Order order) { this.order = order; }
void print() {
System.out.println("Invoice for " + order.customer + ": Rs." + order.amount);
}
}
class Order {
String customer;
double amount;
Invoice invoice;
Order(String customer, double amount) {
this.customer = customer;
this.amount = amount;
}
void confirm() {
this.invoice = new Invoice(this); // pass the current order to Invoice
invoice.print();
}
}
public class OrderDemo {
public static void main(String[] args) {
new Order("Ravi", 1499).confirm(); // Invoice for Ravi: Rs.1499.0
}
} Use 6: returning this for method chaining
- A method that returns
thislets the caller call another method on the same object in one expression. - This "fluent" style is used by
StringBuilder.append, builders, and many libraries. - Real-life example: at a burger counter you say "burger, add cheese, add fries, make it large" in one breath. Each request returns the same order so you can keep adding.
public class BurgerOrder {
private final StringBuilder items = new StringBuilder("Burger");
private int price = 120;
BurgerOrder addCheese() { items.append(" + cheese"); price += 30; return this; }
BurgerOrder addFries() { items.append(" + fries"); price += 60; return this; }
BurgerOrder large() { items.append(" (large)"); price += 40; return this; }
void done() { System.out.println(items + " = Rs." + price); }
public static void main(String[] args) {
new BurgerOrder().addCheese().addFries().large().done();
// Burger + cheese + fries (large) = Rs.250
}
} Where this cannot be used
| Situation | Allowed? | Reason / error |
|---|---|---|
| Instance method, constructor, instance block | Yes | There is a current object |
Static method (including main) | No | "non-static variable this cannot be referenced from a static context" |
| Static block or static field initializer | No | Runs at class loading; no object exists |
Assigning to it: this = other; | No | this is not a variable you can change |
this(...) not as the first statement | No | "call to this must be first statement in constructor" |
this(...) inside a normal method | No | Constructor calls are allowed only in constructors |
| Lambda body inside an instance method | Yes | Refers to the enclosing object (not the lambda) |
| Interface default method | Yes | Refers to the object implementing the interface |
public class StaticError {
int count = 5;
public static void main(String[] args) {
// System.out.println(this.count); // compile error: static context
StaticError obj = new StaticError(); // create an object first
System.out.println(obj.count); // 5
}
} Differences between this and super
| Point | this | super |
|---|---|---|
| Refers to | The current object (as its own class) | The parent-class part of the current object |
| Field access | this.name: field of the current class | super.name: hidden field of the parent |
| Method call | this.show(): current (possibly overriding) version | super.show(): parent version |
| Constructor call | this(...): another constructor of the same class | super(...): a parent constructor |
| Automatic insertion | Never inserted | super() inserted if no this(...) / super(...) |
| Can be passed or returned | Yes: return this;, m(this) | No: super alone is not an expression |
| Static context | Not allowed | Not allowed |
| Real-life | "I will do it myself" | "Let my parent do it the family way" |
Differences between this and this()
| Point | this (keyword reference) | this() (constructor call) |
|---|---|---|
| What it is | Reference to the current object | Call to another constructor of the same class |
| Where allowed | Instance methods, constructors, instance blocks | Only inside constructors |
| Position | Anywhere in those places | Must be the first statement |
| How many times | As many as you like | At most once per constructor |
| Typical use | this.name = name;, return this; | this("guest", 0); |
Advanced — this Keyword
this in inner classes: Outer.this
- Inside a (non-static) inner class, plain
thisis the inner object. The enclosing outer object isOuter.this. - Use
Outer.this.fieldwhen an inner field or parameter hides an outer field with the same name. - A static nested class has no
Outer.this, because it is not tied to an outer object. - Real-life example: a room inside a house. "This room" is the room; "this house" (
House.this) is the building the room belongs to.
public class House {
String name = "Green Villa";
class Room {
String name = "Bedroom";
void describe() {
System.out.println(this.name); // Bedroom (inner object)
System.out.println(House.this.name); // Green Villa (outer object)
}
}
public static void main(String[] args) {
House h = new House();
House.Room r = h.new Room();
r.describe();
}
} this in lambdas vs anonymous classes
- A lambda does not create a new scope for
this. Inside a lambda,thisis the enclosing object. - An anonymous class is a real new object, so
thisinside it refers to the anonymous object itself. - This difference is a favourite interview question and matters when the anonymous class declares a field with the same name.
public class LambdaThis {
String name = "Outer object";
void run() {
Runnable lambda = () -> System.out.println("lambda: " + this.name);
Runnable anon = new Runnable() {
String name = "Anonymous object";
@Override
public void run() {
System.out.println("anonymous: " + this.name);
System.out.println("outer from anonymous: " + LambdaThis.this.name);
}
};
lambda.run(); // lambda: Outer object
anon.run(); // anonymous: Anonymous object
// outer from anonymous: Outer object
}
public static void main(String[] args) {
new LambdaThis().run();
}
} Pitfall: letting this escape from a constructor
- If a constructor passes
thisto other code before all fields are assigned, that code can see a half-built object. - In multithreaded code, another thread may even see
finalfields with default values. - Fix: finish initialization first, and register the object afterwards (for example, from a static factory method).
class Printer {
static void print(Gadget g) {
System.out.println("Printer sees label = " + g.label);
}
static void show(Widget w) {
System.out.println("Printer sees label = " + w.label);
}
}
class Gadget {
final String label;
Gadget(String label) {
Printer.print(this); // escapes too early: label is still null
this.label = label;
}
}
class Widget {
final String label;
private Widget(String label) {
this.label = label; // finish building first
}
static Widget create(String label) {
Widget w = new Widget(label);
Printer.show(w); // share only the fully built object
return w;
}
}
public class EscapeDemo {
public static void main(String[] args) {
new Gadget("Phone"); // Printer sees label = null
Widget.create("Tablet"); // Printer sees label = Tablet
}
} this in equals and compareTo
- In
equals,thisis the left object and the parameter is the right object:a.equals(b)comparesthis(a) witho(b). - The first line
if (this == o) return true;is a fast shortcut when both references point to the same object. - In
compareTo, compare a field ofthiswith the same field of the other object.
import java.util.Objects;
public class Product implements Comparable<Product> {
final String code;
final double price;
Product(String code, double price) { this.code = code; this.price = price; }
@Override
public boolean equals(Object o) {
if (this == o) return true; // same object
if (!(o instanceof Product other)) return false;
return this.code.equals(other.code);
}
@Override
public int hashCode() { return Objects.hash(code); }
@Override
public int compareTo(Product other) {
return Double.compare(this.price, other.price); // cheaper first
}
public static void main(String[] args) {
Product a = new Product("P1", 99);
Product b = new Product("P1", 120);
System.out.println(a.equals(b)); // true (same code)
System.out.println(a.compareTo(b)); // -1 (a is cheaper)
}
} synchronized(this) and locking
synchronizedinstance methods lock onthis.synchronized (this) { ... }does the same for a block.- Any outside code holding a reference can also lock the same object, which can cause unexpected waiting.
- Production code often prefers a private lock object:
private final Object lock = new Object();.
public class Counter {
private int value;
private final Object lock = new Object();
void incrementWithThis() {
synchronized (this) { // lock = this object
value++;
}
}
void incrementWithPrivateLock() {
synchronized (lock) { // nobody outside can grab this lock
value++;
}
}
int get() { synchronized (lock) { return value; } }
} Builder pattern with return this
- Builders collect optional values step by step with methods that
return this, then create an immutable object inbuild(). - This avoids constructors with many parameters, where it is easy to swap two
Stringarguments by mistake.
public class Profile {
private final String name;
private final String city;
private final int age;
private Profile(Builder b) {
this.name = b.name;
this.city = b.city;
this.age = b.age;
}
public String toString() { return name + ", " + age + ", " + city; }
static class Builder {
private String name = "Guest";
private String city = "Unknown";
private int age;
Builder name(String name) { this.name = name; return this; }
Builder city(String city) { this.city = city; return this; }
Builder age(int age) { this.age = age; return this; }
Profile build() { return new Profile(this); }
}
public static void main(String[] args) {
Profile p = new Profile.Builder().name("Asha").age(22).city("Pune").build();
System.out.println(p); // Asha, 22, Pune
}
} Differences between Java this, C++ this, and Python self
| Point | Java this | C++ this | Python self |
|---|---|---|---|
| Type | Reference to the current object | Pointer to the current object | Ordinary first parameter |
| Declared by you? | No (implicit) | No (implicit) | Yes, in every method signature |
| Member access | this.name | this->name or (*this).name | self.name |
| Can be null? | Never inside an instance method | Undefined behaviour if called on null | Not normally |
| Pointer arithmetic | Not possible | Possible (but rarely sensible) | Not applicable |
| Required for fields? | Only when shadowed | Only when shadowed | Always (self.x) |
Tricky Interview Points
Q1) What is the this keyword in Java?
Answer A reference to the current object, the object on which the instance method or constructor is running. It is created implicitly and cannot be reassigned.
Q2) Give a real-life example of this.
Answer The word "my". When Asha says "my roll number" it means Asha, and when Ravi says it, it means Ravi. Inside asha.introduce(), this is asha; inside ravi.introduce(), this is ravi.
Q3) What are the uses of this?
Answer Refer to current-object fields, call current-class methods, call another constructor with this(), pass the current object as a method argument, pass it to a constructor, and return it for method chaining.
Q4) Why do we write this.name = name?
Answer The parameter name shadows the field. this.name refers to the field, name to the parameter. Without this, the parameter is assigned to itself and the field stays at its default.
Q5) What happens if you write name = name in a constructor?
Answer It compiles, but it assigns the parameter to itself. The field keeps its default value (null or 0). It is a silent bug.
Q6) Can you use this in a static method?
Answer No. Static methods have no current object, so the compiler reports "non-static variable this cannot be referenced from a static context".
Q7) What is this()? Where can it appear?
Answer A call to another constructor of the same class. It can appear only inside a constructor, as the first statement, and at most once.
Q8) Can this() and super() be used together?
Answer No. Both must be the first statement of a constructor, so only one can be used.
Q9) Difference between this and super?
Answer this refers to the current object and its class members and constructors; super refers to the parent-class members and constructors of the same object.
Q10) Difference between this and this()?
Answer this is a reference to the current object usable anywhere in instance code. this() is a constructor call allowed only as the first statement in a constructor.
Q11) Can we return this from a method? Why?
Answer Yes. Returning this enables method chaining, as in StringBuilder.append or builder classes: new Order().addCheese().addFries().done().
Q12) Can we assign a value to this?
Answer No. this = other is a compile error. this always refers to the current object.
Q13) What is Outer.this?
Answer Inside an inner class, Outer.this refers to the enclosing outer object, while plain this refers to the inner object.
Q14) What does this refer to inside a lambda?
Answer The enclosing object, because lambdas do not introduce a new this. In an anonymous class, this refers to the anonymous object itself.
Q15) Is Java this a pointer like in C++?
Answer No. It is a reference: no pointer arithmetic, no -> operator, and it is never null inside an instance method.
Q16) What is the risk of passing this from a constructor?
Answer This "escaping" exposes a partially constructed object; other code or threads may see fields before they are assigned.
Q17) Can this be null?
Answer No. An instance method can only run on an existing object. Calling a method on a null reference throws NullPointerException before the method starts.
Simple Programs
Shadowing bug and fix: Employee with and without this
public class EmployeeThis {
int id;
String name;
double salary;
EmployeeThis(int id, String name, double salary) {
this.id = id; // remove "this." and all fields stay default
this.name = name;
this.salary = salary;
}
void display() {
System.out.println(this.id + " | " + this.name + " | Rs." + this.salary);
}
public static void main(String[] args) {
new EmployeeThis(501, "Meena", 45000).display(); // 501 | Meena | Rs.45000.0
}
} Bank account: compare two objects using this
public class Account {
String holder;
double balance;
Account(String holder, double balance) {
this.holder = holder;
this.balance = balance;
}
Account richer(Account other) {
return this.balance >= other.balance ? this : other;
}
void transferTo(Account other, double amt) {
if (amt > this.balance) {
System.out.println("Insufficient balance in " + this.holder);
return;
}
this.balance -= amt;
other.balance += amt;
System.out.println(this.holder + " sent Rs." + amt + " to " + other.holder);
}
public static void main(String[] args) {
Account a = new Account("Ravi", 5000);
Account b = new Account("Priya", 8000);
System.out.println("Richer: " + a.richer(b).holder); // Priya
a.transferTo(b, 2000); // Ravi sent Rs.2000.0 to Priya
System.out.println(a.balance + " " + b.balance); // 3000.0 10000.0
}
} Shopping cart with method chaining
import java.util.ArrayList;
import java.util.List;
public class Cart {
private final List<String> items = new ArrayList<>();
private double total;
Cart add(String item, double price) {
this.items.add(item);
this.total += price;
return this;
}
Cart applyCoupon(double percent) {
this.total -= this.total * percent / 100;
return this;
}
void checkout() {
System.out.println(items + " -> Rs." + total);
}
public static void main(String[] args) {
new Cart().add("Pen", 20).add("Notebook", 80).add("Bag", 900).applyCoupon(10).checkout();
// [Pen, Notebook, Bag] -> Rs.900.0
}
} Teacher and student: passing this as an argument
import java.util.ArrayList;
import java.util.List;
class Teacher {
String name;
List<Pupil> pupils = new ArrayList<>();
Teacher(String name) { this.name = name; }
void enroll(Pupil p) {
pupils.add(p);
p.teacher = this; // link back using this
}
}
class Pupil {
String name;
Teacher teacher;
Pupil(String name) { this.name = name; }
void joinClassOf(Teacher t) {
t.enroll(this); // pass myself
}
}
public class ClassroomDemo {
public static void main(String[] args) {
Teacher t = new Teacher("Mrs. Rao");
new Pupil("Asha").joinClassOf(t);
new Pupil("Ravi").joinClassOf(t);
for (Pupil p : t.pupils) System.out.println(p.name + " -> " + p.teacher.name);
// Asha -> Mrs. Rao
// Ravi -> Mrs. Rao
}
} Constructor chaining with this() for a laptop configuration
public class Laptop {
String brand;
int ramGb;
int storageGb;
Laptop(String brand) { this(brand, 8); }
Laptop(String brand, int ramGb) { this(brand, ramGb, 512); }
Laptop(String brand, int ramGb, int ssdGb) {
this.brand = brand;
this.ramGb = ramGb;
this.storageGb = ssdGb;
}
public String toString() { return brand + " " + ramGb + "GB RAM, " + storageGb + "GB SSD"; }
public static void main(String[] args) {
System.out.println(new Laptop("Dell")); // Dell 8GB RAM, 512GB SSD
System.out.println(new Laptop("HP", 16)); // HP 16GB RAM, 512GB SSD
System.out.println(new Laptop("Lenovo", 32, 1024)); // Lenovo 32GB RAM, 1024GB SSD
}
} Outer.this with a bank and its branch
public class Bank {
String name = "LCG Bank";
double interestRate = 6.5;
class Branch {
String name;
Branch(String name) { this.name = name; }
void info() {
System.out.println(this.name + " branch of " + Bank.this.name
+ " offers " + Bank.this.interestRate + "%");
}
}
public static void main(String[] args) {
Bank bank = new Bank();
Bank.Branch b1 = bank.new Branch("Ameerpet");
Bank.Branch b2 = bank.new Branch("Madhapur");
b1.info(); // Ameerpet branch of LCG Bank offers 6.5%
b2.info(); // Madhapur branch of LCG Bank offers 6.5%
}
} Proving this is the calling object
public class Identity {
String tag;
Identity(String tag) { this.tag = tag; }
void check(Identity ref) {
System.out.println(tag + ": this == ref ? " + (this == ref));
}
public static void main(String[] args) {
Identity x = new Identity("x");
Identity y = new Identity("y");
x.check(x); // x: this == ref ? true
x.check(y); // x: this == ref ? false
y.check(y); // y: this == ref ? true
}
} Problem Solving Tricks
- Read
thisas "my":this.namemeans "my name" for whichever object is running the method. - If a constructor parameter has the same name as a field, you must write
this.field = param. - If fields stay
nullor0after construction, look for a missingthis.first. - No
thisinmainor any static method; create an object and use its reference instead. this(...)must be the first line of a constructor, and you cannot also writesuper(...)there.return this;turns setters into chainable calls (builders, carts, query objects).- In an inner class, use
Outer.thisto reach the outer object. - In a lambda,
thisis the enclosing object; in an anonymous class, it is the anonymous object. - Do not pass
thisto other code from inside a constructor before every field is set. - Starting
equalswithif (this == o) return true;is a cheap and standard shortcut.
Practice Programs List
- Write a
Studentclass where removingthis.silently leaves fieldsnull; then fix it withthis. - Write a
Billclass whosetotal()method callsthis.tax()and print the result. - Create a
MovieTicketclass with two constructors chained usingthis(). - Write a
Patientclass with acheckIn(Reception r)method that passesthisto the reception. - Write
OrderandInvoiceclasses where the order createsnew Invoice(this). - Build a
BurgerOrderorCartclass with at least three chainable methods thatreturn this. - Write a method
richer(Account other)that returnsthisorotherbased on the balance. - Try to use
thisinsidemainand write down the exact compiler error. - Create an inner class
RoominsideHouseand print boththis.nameandHouse.this.name. - Compare
thisinside a lambda and inside an anonymousRunnablein the same method. - Implement
equalsandcompareTofor aProductclass usingthisand the other object. - Demonstrate the escaping-this problem by printing a field from a method called inside the constructor before assignment.
- Write a
Profile.Builderwith fluent setters and abuild()method. - Write a table comparing
thisandsuperfor aVehicleandCarexample, then code each row.