區分Java的方法覆蓋與變數覆蓋_java

來源:互聯網
上載者:User

首先,我們看看關於重載,和覆蓋(重寫)的簡明定義:

方法重載:如果有兩個方法的方法名相同,但參數不一致,哪麼可以說一個方法是另一個方法的重載。

方法覆蓋:如果在子類中定義一個方法,其名稱、傳回型別及參數簽名正好與父類中某個方法的名稱、傳回型別及參數簽名相匹配,那麼可以說,子類的方法覆蓋了父類的方法

我們重點說說覆蓋問題,以如下代碼為例:

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   } 

顯然,如此的覆蓋,才是對我們更有用的覆蓋,因為這樣才能達到:把具體對象抽象為一般對象的目的,實同多態性

以上只是我個人的看法,有不對的地方歡迎指出來討論。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.