Huron High School AP Computer Science Instructor: Kevin Behemer S. Teacher: Guillermo Moreno
The this keyword The this keyword refers to the object that is currently executing. It is useful for a method to reference instance variables relative to this.
Example: this.varName varName is the name of an instance variable.
Another use: Allows one constructor to explicitly invoke another constructor in the same class. this ( args );
args is an optional set of arguments that maybe passed to a constructor. Only use this syntax as the first line in a constructor.
Class Point3D { double x; double y; double z; Point3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; }//end of constructor }//end of class Point3D
Class ThisKeywordDemo { public static void main(String args[]) { Point3D p = new Point3D(1.1, 3.4, -2.8); System.out.println(“p.x = “ + p.x); System.out.println(“p.y = “ + p.y); System.out.println(“p.z = “ + p.z); }//end of main function }//end of class ThisKeywordDemo
Output: p.x = 1.1 p.y = 3.4 p.z = -2.8