this可能是幾乎所有有一點(diǎn)面向?qū)ο笏枷氲恼Z(yǔ)言都會(huì)引用到的變量,java自然不例外。只是,this有多少種用法,我也不知道了,讓我們來(lái)see see。
由簡(jiǎn)入奢! 易。
來(lái)個(gè)例子說(shuō)明下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
public class debugertest { public static void main(string[] args) { userexample samp1 = new userexample( "amy" ); system.out.println( "who are u? " ); system.out.println(samp1.whoareu()); system.out.println( "intro yourself?" ); system.out.println(samp1.introyourself()); } } class userexample { private string name; private integer age; private mydoll mydoll; public userexample() { this ( null ); } // 3. 調(diào)用本類的其他構(gòu)造方法 public userexample(string name) { this (name, - 1 ); } public userexample(string name, integer age) { this .name = name; this .age = age; this .mydoll = new mydoll( "prize" ); } // 2. 調(diào)用本類屬性 public void changemyname(string name) { this .name = name; } public void changemyage(integer age) { this .age = age; } public string whoareu() { return "i am " + name + ". " ; } public string haooldareu() { return "i am " + age + " old." ; } // 1. 調(diào)用本類方法 public string introyourself() { return this .whoareu() + this .haooldareu() + "\r\n whoami@ " + this .mydoll.whoami() + "\r\n whoaresuper@ " + this .mydoll.whoaresuper(); } class mydoll { private string name; public mydoll(string name) { this .name = name; } public void changemyname(string name) { this .name = name; } // 5. 隱藏式的調(diào)用 public string whoami() { return whoareu(); } public string whoareu() { return "i am a doll, my name is " + name + ". " ; } // 4. 調(diào)用父類的或指定的其他的類的同名方法 public string whoaresuper() { return "super is " + userexample. this .whoareu() + ". " ; } } } |
1. 調(diào)用本類方法,表達(dá)更清晰
1
2
3
|
public string introyourself() { return this .whoareu() + this .haooldareu(); } |
2. 調(diào)用本類屬性,基本功亮出來(lái)
1
2
3
|
public void changemyname(string name) { this .name = name; } |
3. 調(diào)用本類的其他構(gòu)造方法,更靈活
1
2
3
|
public userexample(string name) { this (name, - 1 ); } |
4. 調(diào)用父類的或指定的其他的類的同名方法,為避免歧義而生的方法
1
2
3
|
public string whoaresuper() { return "super is " + userexample. this .whoareu() + ". " ; } |
5. 隱藏式的調(diào)用,為了寫代碼方便(更常用),不指定范圍,java會(huì)在全類范圍內(nèi)向上查找變量或方法
1
2
3
|
public string whoami() { return whoareu(); } |
以上樣例輸出結(jié)果如下所示:
this是個(gè)基本的關(guān)鍵字,我們平時(shí)也一直在用,只是也不一定所有同學(xué)都清楚怎么用。
總結(jié)
以上所述是小編給大家介紹的java中this的n種使用方法,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:https://www.cnblogs.com/yougewe/p/9468960.html