- Java面向對象軟件開發
- 姚駿屏 汪衛星主編
- 530字
- 2018-12-29 19:04:17
2.2.4 super關鍵字
當對父類實施成員覆蓋以后,如果仍然需要使用父類的同名方法怎么辦?這就要使用super關鍵字。super表示當前對象的直接父類對象。super的使用方法有以下三種:
(1)用來訪問直接父類中被隱藏的數據成員。其使用形式如下:
super.數據成員
(2)用來訪問直接父類中被重寫的成員方法。其使用形式如下:
super.成員方法
(3)用來調用直接父類的構造方法。其使用形式如下:
super ([參數列表])
特別提示:
如果父類的構造方法為有參構造方法,則子類的構造方法中必須用super ([參數列表])給父類傳參。
【例2-7】 在子類B中定義了與父類同名的屬性z和方法display(),從而隱藏了父類同名成員,但在子類中又要求能調用到父類的方法和屬性。
// 父類A class A { int x, y; int z = 100; public A(int x,int y){ // 構造方法 this.x = x; this.y = y; } public void display() { System.out.println("In class A: x= " + x + " , y= " + y); } } // 子類B,繼承于父類A class B extends A { int a, b; int z=200; // 在子類中定義與父類同名變量z public B(int x,int y,int a,int b){ // 構造方法 super(x,y); // 調用父類的構造方法,必須是子類構造方法的第一個可執行語句 this.a = a; this.b = b; } public void display(){ // 重寫父類的display()方法 super.display(); // 調用父類中被重寫的方法 System.out.println("In class B: a= " + a + " , b= " + b); System.out.println("Subclass B:"+z); // 直接輸出為子類變量 System.out.println("Superclass A:"+super.z); // 訪問父類變量 } } public class SuperDemo { public static void main(String[] args) { B a = new B(1, 2, 3, 4); a.display(); } }
該程序的運行結果如下:
In class A: x= 1 , y= 2 In class B: a= 3 , b= 4 Subclass B: 200 Superclass A: 100
推薦閱讀
- Mastering phpMyAdmin 3.4 for Effective MySQL Management
- Python程序設計案例教程
- Redis Essentials
- ADI DSP應用技術集錦
- 青少年學Python(第1冊)
- Java Web從入門到精通(第3版)
- 零基礎學C語言(升級版)
- Learning Jakarta Struts 1.2: a concise and practical tutorial
- Java 9 with JShell
- 游戲設計的底層邏輯
- Building Apple Watch Projects
- SOA Patterns with BizTalk Server 2013 and Microsoft Azure(Second Edition)
- PHP典型模塊與項目實戰大全
- 移動智能系統測試原理與實踐
- Delphi Cookbook