← Back to course

Instance Variables & this

You’ll be able to

this refers to the current object

Inside an instance method or constructor, this is a reference to the object the method was called on. When you write p.getX(), inside getX the keyword this refers to p. Every object has its own copy of the instance variables, and this is how a method names the copy belonging to the object it is working on.

Using this to disambiguate

When a constructor’s parameter has the same name as an instance variable, the parameter shadows the field. Writing this.x = x; assigns the parameter x to the instance variable this.x. Without this, x = x would just assign the parameter to itself, leaving the field unchanged — a subtle and common bug.

Default values of instance variables

Instance variables that you never assign take default values: numeric fields (int, double) default to 0 / 0.0, boolean to false, and object references (like String) to null. This differs from local variables inside methods, which have no default and must be assigned before use.

this to resolve shadowing
public Point(int x) { this.x = x; }
`this.x` is the instance variable; the bare `x` is the parameter. `this` picks the field when the names collide.
Worked example

Given class Point { private int x; public Point(int x) { this.x = x; } public int getX() { return x; } }, trace: Point p = new Point(9); then System.out.println(p.getX());

  1. 1.new Point(9) runs the constructor with parameter x = 9.
  2. 2.this.x = x copies the parameter 9 into the instance variable this.x.
  3. 3.p.getX() returns the instance variable x, which is 9.
Answer: It prints 9this.x = x correctly stored the argument in the field.
Checkpoint

Given `class Point { private int x; public Point(int x) { this.x = x; } public int getX() { return x; } }`, what does this print? `Point p = new Point(9);` then `System.out.println(p.getX());`

Watch out

Inside a constructor with a same-named parameter, x = x assigns the parameter to itself and leaves the field at its default. You need this.x = x to actually set the instance variable.

Checkpoint

Given `class Box { private int size; public int getSize() { return size; } }`, what does this print? `Box b = new Box();` then `System.out.println(b.getSize());`

On the exam

Remember the split: instance variables default (int → 0, boolean → false, object → null), but local variables must be initialized before use or the code will not compile.

Answer the 2 checkpoints as you read.

Sign in to save your progress