cs176:501b:this_keyword
The "this" keyword
- The “this” reference variable
- “this” is the name of a reference variable that an object can use to refer to itself.
- Can be used in only non-static methods.
- Common use of “this” is to overcome “shadowing” in “set” methods:
- See notes on "shadowing".
public class Rectangle { private int width; private int height; // setHeight method of Rectangle class: public void setHeight( int height ) { height = height; // ??? Shadowing: Which height is which ??? } } public class Rectangle { private int width; private int height; // Avoid shadowing using "this": public void setHeight( int height ) { this.height = height; // "This" Rectangle's instance variable height // is equal to the value of the input parameter // variable height. } }
cs176/501b/this_keyword.txt · Last modified: 2014/06/11 18:58 by jchung