Instance Variables & this
- Explain what the `this` keyword refers to inside a method
- Use `this` to disambiguate a parameter from an instance variable
- Recall the default values of uninitialized instance variables
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.
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.
new Point(9)runs the constructor with parameterx = 9. - 2.
this.x = xcopies the parameter 9 into the instance variablethis.x. - 3.
p.getX()returns the instance variablex, which is 9.
9 — this.x = x correctly stored the argument in the field.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());`
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.
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());`
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