Definition of this:
Use of this within methods:
Example without this:
class Pwr { double b; int e; double val; Pwr(double base, int exp) { b = base; e = exp; val = 1; if (exp == 0) return; for (; exp > 0; exp--) val = val * base; } double get_pwr() { return val; } }
Explicit use of this:
class Pwr { double b; int e; double val; Pwr(double b, int e) { this.b = b; this.e = e; this.val = 1; if (e == 0) return; for (; e > 0; e--) this.val = this.val * b; } double get_pwr() { return this.val; } }
When to use this:
Useful for accessing instance variables when names conflict with local variables or parameters.
In constructor methods, to reference the object under construction.
class Pwr { double b; int e; double val; Pwr(double base, int exp) { this.b = base; this.e = exp; this.val = 1; if (exp == 0) return; for (; exp > 0; exp--) this.val = this.val * base; } double get_pwr() { return this.val; } } class DemoPwr { public static void main(String args[]) { Pwr x = new Pwr(4.0, 2); Pwr y = new Pwr(2.5, 1); Pwr z = new Pwr(5.7, 0); System.out.println(x.b + " raised to the " + x.e + " power is " + x.get_pwr()); System.out.println(y.b + " raised to the " + y.e + " power is " + y.get_pwr()); System.out.println(z.b + " raised to the " + z.e + " power is " + z.get_pwr()); } }
Explanation:
The above is the detailed content of The this keyword. For more information, please follow other related articles on the PHP Chinese website!