首先,我們看看關於重載,和覆蓋(重寫)的簡明定義:
方法重載:如果有兩個方法的方法名相同,但參數不一致,哪麼可以說一個方法是另一個方法的重載。
方法覆蓋:如果在子類中定義一個方法,其名稱、返回類型及參數簽名正好與父類中某個方法的名稱、返回類型及參數簽名相匹配,那麼可以說,子類的方法覆蓋了父類的方法
我們重點說說覆蓋問題,以如下代碼爲例:
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方法成功覆蓋了父類的方法
我們再來看看變量的覆蓋:
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
}
通過運行結果我發現:變量的覆蓋實際上與方法的不盡相同.
用我自己的話說:變量的覆蓋最多隻能算是半吊子的覆蓋.
要不然,向上轉換與不會發生數據丟失現象
People pp=new Student();
System.out.println(pp.name);//運行結果爲people
就我個人的經驗來說:變量的覆蓋很容易讓人犯錯誤.讓人感覺又回到了C++的繼承[這裏不是指C++帶virtual的繼承]
最後我們再來看一段代碼:
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
}
顯然,如此的覆蓋,纔是對我們更有用的覆蓋,因爲這樣才能達到:把具體對象抽象爲一般對象的目的,實同多態性
以上只是我個人的看法,有不對的地方歡迎指出來討論.