What is `this`?
java
public class Dog {
private String name;
public Dog(String name) {
this.name = name; // this.name = the instance variable
// name = the parameter
}
public void introduce() {
System.out.println("I am " + this.name);
// same as: System.out.println("I am " + name);
}
}
Dog d = new Dog("Max");
d.introduce(); // "I am Max" — this refers to d
Primary use: disambiguating names
java
public class Point {
private int x;
private int y;
// Without this — WRONG!
public Point(int x, int y) {
x = x; // assigns parameter to itself! Instance variable unchanged!
y = y; // same problem!
}
// With this — CORRECT!
public Point(int x, int y) {
this.x = x; // this.x = instance variable, x = parameter
this.y = y; // this.y = instance variable, y = parameter
}
}
What happens without `this`?
java
public Point(int x, int y) {
x = x; // parameter x = parameter x (useless)
}
Point p = new Point(3, 5);
// p.x is still 0! The instance variable was never set!
When `this` is optional
java
public class Circle {
private double radius;
// No conflict — this is optional
public double getArea() {
return Math.PI * radius * radius;
// same as: return Math.PI * this.radius * this.radius;
}
}
java
public void setRadius(double radius) {
this.radius = radius; // this is REQUIRED here
}
Using `this` to pass the current object
java
public class Student {
private String name;
public Student(String name) {
this.name = name;
}
public void enrollIn(Course course) {
course.addStudent(this); // pass THIS student to the course
}
}
Using `this` to return the current object
java
public class Builder {
private String name;
private int age;
public Builder setName(String name) {
this.name = name;
return this; // returns the current object
}
public Builder setAge(int age) {
this.age = age;
return this;
}
}
// Method chaining
Builder b = new Builder().setName("Alice").setAge(20);
`this` with multiple objects
java
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public boolean isBiggerThan(Circle other) {
return this.radius > other.radius;
// this = the circle calling the method
// other = the circle passed as argument
}
}
Circle c1 = new Circle(5);
Circle c2 = new Circle(3);
c1.isBiggerThan(c2); // this = c1, other = c2 → true
c2.isBiggerThan(c1); // this = c2, other = c1 → false
Trace practice
java
public class Counter {
private int value;
public Counter(int value) {
this.value = value;
}
public Counter add(Counter other) {
this.value += other.value;
return this;
}
public int getValue() { return value; }
}
Counter a = new Counter(10);
Counter b = new Counter(5);
Counter c = new Counter(3);
a.add(b).add(c); // chain!
AP Exam Tips
- •
- •
- •
- •
Common Mistakes
- •
- •
- •