this
總要有個(gè)事物來代表類的當(dāng)前對象,就像C++中的this指針一樣,Java中的this關(guān)鍵字就是代表當(dāng)前對象的引用。
它有三個(gè)主要的作用:
1、在構(gòu)造方法中調(diào)用其他構(gòu)造方法。
比如有一個(gè)Student類,有三個(gè)構(gòu)造函數(shù),某一個(gè)構(gòu)造函數(shù)中調(diào)用另外構(gòu)造函數(shù),就要用到this(),而直接使用Student()是不可以的。
2、返回當(dāng)前對象的引用。
3、區(qū)分成員變量名和參數(shù)名。
看下面的例子:
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
|
public class Student { private String name; private int age; private String college; public Student() { age = 20 ; } public Student(String name) { this (); //can not be call Student,only use this() method. this .name = name; System.out.println( "this student name is " +name); } public Student(String name,String college) { this (name); //C++中可以直接用Student(name)調(diào)用其他構(gòu)造函數(shù) this .college = college; System.out.println( "this student name is " +name+ " college is " +college); } public Student upgrade() { age++; return this ; } public void print() { System.out.println( "name is: " +name + " age is: " +age + " college is: " +college); } public static void main(String[] args) { Student student1 = new Student( "linc" ); Student student2 = new Student( "linc" , "shenyang college" ); student2.upgrade().print(); } } |
迷失在茫茫的對象海洋時(shí),不要忘了用this來找到自我。
super
super是this的父輩。從面相對象的角度說,這兩個(gè)概念是很好理解的。
子類從父類繼承過來,父類的protected及以上的屬性和方法在子類中是天生就具有的。那么,為什么還要有super這個(gè)關(guān)鍵字?
第一、看父類的構(gòu)造
子類構(gòu)造時(shí)要先調(diào)用父類的默認(rèn)構(gòu)造函數(shù)的,這與C++的構(gòu)造屬性一致。當(dāng)父類有多個(gè)構(gòu)造函數(shù)時(shí),你需要指定調(diào)用哪個(gè)。這是就需要使用super(arg1,arg2...)。
需要注意的是,在子類的構(gòu)造函數(shù)中調(diào)用基類的構(gòu)造函數(shù)時(shí),必須要把super寫作最前面,否則報(bào)錯(cuò)。
第二,在子類覆蓋父類的一些方法中再調(diào)用父類的此方法。大家都知道,在子類中覆蓋父類的一些方法是面向?qū)ο笾卸鄳B(tài)的一種方式,而因?yàn)槠渌N種原因,需要在此方法中調(diào)用父類的此方法,用以區(qū)分,此時(shí)需要使用super來完成。
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
|
public class ClassLeader extends Student { private String duty; public ClassLeader() { duty = "class monitor" ; } public ClassLeader(String duty,String name,String college) { super (name,college); this .duty = duty; } public void print() { super .print(); System.out.println( "duty is " + duty); } public static void main(String[] args) { ClassLeader leader = new ClassLeader( "life" , "linc" , "shenyang" ); leader.print(); } } |
將兩個(gè)類文件放在同一個(gè)目錄,編譯并運(yùn)行:
1
2
3
|
D:\workspace\Java\project261\super>javac -d . *java D:\workspace\Java\project261\super>java ClassLeader |
運(yùn)行結(jié)果:
1
2
3
4
|
this student name is linc this student name is linc college is shenyang name is: linc age is: 20 college is: shenyang duty is life |
看看在其他語言中是怎樣來處理的:
C#中提供了base關(guān)鍵字來完成super相似的功能,C++直接用基類的名字來調(diào)用。