此定義:
在方法中使用此:
沒有這個的例子:
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; } }
明確使用此:
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; } }
何時使用此:
當名稱與局部變數或參數衝突時,對於存取實例變數很有用。
在建構函式方法中,引用正在建構的物件。
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()); } }
解釋:
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3