首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 方法覆寫與變數遮蔽深度解析:多態實現的關鍵差異

     編輯:Java 相關知識

核心定義

  • 方法重載:同類中方法名相同、參數列表不同(類型/個數/順序)
  • 方法覆寫:子類定義與父類同名、同返回類型、同參數簽名的方法

方法覆寫:完整支援多態

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();      // 輸出: people
    Student s = new Student();    // 輸出: student
    People pp = new Student();    // 輸出: student ← 關鍵:多態生效
}

子類方法成功覆寫父類方法,向上轉型時調用的是子類實現。

變數遮蔽:非真正覆寫,無多態行為

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();      // 輸出: people
    Student s = new Student();    // 輸出: student
    People pp = new Student();    // 輸出: people ← 關鍵:父類變數
}

變數遮蔽只是「半吊子的覆寫」:向上轉型後訪問的是父類變數,違背多態預期,極易導致錯誤。

最佳實踐:封裝變數、提供覆寫方法

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; } // 覆寫方法返回自類變數
}

People pp = new Student();
System.out.println(pp.getName()); // 輸出: student ← 正確多態

透過方法覆寫包裝變數訪問,才能真正實現「將具體對象泛化為通用對象」的多態目標。

總結

  • 方法覆寫支援動態綁定,是多態基石
  • 變數遮蔽為靜態綁定,向上轉型訪問父類變數
  • 開發中應避免直接訪問繼承鏈中的同名變數
  • 封裝變數、暴露方法,由子類覆寫方法實現差異化行為
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved