首先,我們看看關于重載,和覆蓋(重寫)的簡明定義:
方法重載:如果有兩個方法的方法名相同,但參數不一致,哪么可以說一個方法是另一個方法的重載。
方法覆蓋:如果在子類中定義一個方法,其名稱、返回類型及參數簽名正好與父類中某個方法的名稱、返回類型及參數簽名相匹配,那么可以說,子類的方法覆蓋了父類的方法
我們重點說說覆蓋問題,以如下代碼為例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public class People { public String getName() { return "people"; } } public class Student extends People { public String getName() { return "student"; } } public static void main(String[] args) { People p=new People(); System.out.println(p.getName());//運行結果為people Student s=new Student(); System.out.println(s.getName());//運行結果為student People pp=new Student(); System.out.println(pp.getName());//運行結果為student } |
上述結果說明:student類的getName方法成功覆蓋了父類的方法
我們再來看看變量的覆蓋:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public class People { protected String name= "people" ; } public class Student extends People { protected String name= "student" ; } public static void main(String[] args) { People p= new People(); System.out.println(p.name); //運行結果為people Student s= new Student(); System.out.println(s.name); //運行結果為student People pp= new Student(); System.out.println(pp.name); //運行結果為people } |
通過運行結果我發現:變量的覆蓋實際上與方法的不盡相同。
用我自己的話說:變量的覆蓋最多只能算是半吊子的覆蓋。
要不然,向上轉換與不會發生數據丟失現象
1
2
|
People pp=new Student(); System.out.println(pp.name);//運行結果為people |
就我個人的經驗來說:變量的覆蓋很容易讓人犯錯誤.讓人感覺又回到了C++的繼承[這里不是指C++帶virtual的繼承]
最后我們再來看一段代碼:
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
|
public class People { protected String name= "people" ; public String getName() { return name; } } public class Student extends People { protected String name= "student" ; public String getName() { return name; } } main(String[] args) { People p= new People(); System.out.println(p.getName()); //運行結果為people Student s= new Student(); System.out.println(s.getName()); //運行結果為student People pp= new Student(); System.out.println(pp.getName()); //運行結果為student } |
顯然,如此的覆蓋,才是對我們更有用的覆蓋,因為這樣才能達到:把具體對象抽象為一般對象的目的,實同多態性
以上只是我個人的看法,有不對的地方歡迎指出來討論。