super:可以用來修飾屬性 方法 構造器
當子類與父類中有同名的屬性時,可以通過 super.此屬性 顯式的調用父類聲明的屬性
若想調用子類的同名的屬性“this.此屬性”
2.當子類重寫父類的方法以后,在子類中若想再顯式的調用父類的被重寫的方法,就需要使用 super.方法
3.super修飾構造器:通過在子類中使用“super(形參列表)”來顯示的調用父類中指定的構造器
>在構造器內部,super(形參列表) 必須聲明在首行
>在構造器內部,this(形參列表)或super(形參列表) 只能出現一個
>當構造器中,不是顯示調用this(形參列表) 或super(形參列表)其中任何一個默認調用的是父類空參的構造器
建議:當設計一個類時,盡量要提供一個空參的構造器。
Person:
package com.aff.sup; public class Person { protected String name; private int age; int id = 1001;// 身份證號 public Person() { this.name = "AA"; this.age = 1; } public Person(String name) { this(); this.name = name; } public Person(String name, int age) { this(name); this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void eat() { System.out.println("eating"); } public void sleep() { System.out.println("sleeping"); this.eat(); } // 比較當前對象與形參的對象的age誰大 public int compare(Person p) { if (this.age > p.age) { return 1; } else if (this.age < p.age) { return -1; } else { return 0; } } }
Student:
package com.aff.sup; public class Student extends Person { private String schoolName; int id = 1002;// 學號 public Student() { super(); } public void eat(){ System.out.println("學生吃飯"); } public void info(){ this.eat(); super.eat(); super.sleep();//寫成this.sleep也行 反正只有一個 } public void show() { System.out.println(this.id);// 1002 System.out.println(super.id);// 1001 調用父類的id System.out.println(super.name); } }
TestStudent:
package com.aff.sup; public class TestStudent { public static void main(String[] args) { Student s = new Student(); s.show(); s.info(); } }
輸出結果:
1002
1001
AA
學生吃飯
eating
sleeping
學生吃飯