Overview


The keyword this is usually optional, but there are some cases where it is required. Let's look at an example.

Ambiguous Reference Issue


Here we have an ambiguous reference (a problem).

When we say "width = width" are we referring to the ivar width or the method parameter width?
public class Rectangle {
	private int width;
	private int height;

	public void setWidth1(int width) {
		width = width
	}
}

Ambiguous Reference Issue Fixed Using 'this'


We solve the ambiguity issue by explicitly reference the ivar width using this.

Java looks in the smaller/local context (method context) before looking in a higher context (class context). That's why it finds the method parameter "width" before the ivar "width".
public class Rectangle {
	private int width;
	private int height;

	public void setWidth1(int width) {
		this.width = width
	}
}