Unit 3 · Class Creation · Topic 3.9this Keyword
Skill 2.B
Big idea: Inside an instance method or constructor, this means "the object this code is running on."
Learning objectives- Develop code for expressions that are self-referencing and determine the result of these expressions.
Fixing shadowing with this
this.width always means the instance variable, even when a parameter is also called width.
public class Rectangle {
private int width;
private int height;
public Rectangle(int width, int height) {
this.width = width; // this.width is the instance variable
this.height = height; // height alone is the parameter
}
public void badSetWidth(int width) {
width = width; // assigns the parameter to itself!
}
public void setWidth(int width) {
this.width = width;
}
public int area() { return width * height; }
}
Passing the current object
this can be passed as an argument so another method receives the current object.
CodePlayer p = new Player("Zed", 30);
Player q = new Player("Ann", 45);
System.out.println(p.beats(q) + " " + q.beats(p));
Outputfalse true
Key points- In an instance method or constructor,
this refers to the current object. this can be passed as an argument.- Static methods have no
this.
Watch outthis.name = name; fixes the shadowing problem from 3.8.
Quick checkCan you use this inside public static void main?Show answer
No. main is static, so there is no current object.