1. super了解為:父類的
2. super可以用來調用:屬性、方法、構造器
3. super的使用
3.1我們可以在子類的方法或構造器中。通過使用"super.屬性"或"super.方法"的方式,顯式的調用父類中聲明的屬性或方法。但是,通常情況下,我們習慣省略"super."
3.2特殊情況:當子類和父類中定義了同名的屬性時,我們要想在子類中調用父類中聲明的屬性,則必須顯式的使用"super.屬性"的方式,表明調用的是父類中聲明的屬性。
3.3特殊情況:當子類重寫了父類中的方法以後,我們想在子類的方法中調用父類中被重寫的方法時,則必須顯式的使用"super.方法"的方式,表明調用的是父類中被重寫的方法。
Person類
package com.binbin.test02;
public class Person {
int id = 1001;
String name;
int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void eat() {
System.out.println("人可以吃飯");
}
}
複制
Student類
測試package com.binbin.test02;
public class Student extends Person {
int id = 2001;
char sex;
public Student() {
}
public Student(String name, int age, char sex) {
super(name, age); // 構造器使用super的方法
this.sex = sex;
}
public void showInfo() {
System.out.println("this id:" + this.id + ", name: " + name + ", sex:" + sex + ", age: " + age);
System.out.println("super id " + super.id);
this.eat(); // 目前類的eat方法
System.out.println();
super.eat(); // 父類的eat方法
}
@Override
public void eat() {
System.out.println("重寫:人可以吃有營養的飯~~");
}
}
複制
測試類
package com.binbin.test02;
public class SuperTest {
public static void main(String[] args) {
Student s = new Student();
s.showInfo();
Student s1 = new Student("Tom", 32, '男');
s1.showInfo();
}
}
複制
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAjM2EzLcd3LcJzLcJzdllmVldWYtl2Pn5GcuM2YkFjN0cDMlJjMkJWOwQTNklTO0UTYxMDM1cTNwIGMvwVO5MTO3EzNtUGall3LcVmdhNXLwRHdo9CXt92YucWbpRWdvx2Yx5yazF2Lc9CX6MHc0RHaiojIsJye.png)
運作結果