在 Java 面向對象編程中,this 與 super 是兩個核心關鍵字,分別代表當前對象引用與父類引用。正確理解它們的用法對於構建清晰的類繼承體系至關重要。本文通過實例代碼詳細講解兩者的三大核心用法。
this 代表當前類的實例引用,主要有三大作用:
this.變量名 明確指代實例變量。public class Student {
private String name;
private int age;
private String college;
public Student() {
age = 20;
}
public Student(String name) {
this(); // 調用無參構造器
this.name = name; // 區分參數與成員變量
System.out.println("this student name is " + name);
}
public Student(String name, String college) {
this(name); // 調用單參構造器
this.college = college;
System.out.println("this student name is " + name + " college is " + college);
}
public Student upgrade() {
age++;
return this; // 返回當前對象引用,支持鏈式調用
}
public void print() {
System.out.println("name is: " + name + " age is: " + age + " college is: " + college);
}
public static void main(String[] args) {
Student student1 = new Student("linc");
Student student2 = new Student("linc", "shenyang college");
student2.upgrade().print(); // 鏈式調用
}
}
super 代表父類引用,主要用於:
super(參數列表)。super.方法名()。super.變量名。public class ClassLeader extends Student {
private String duty;
public ClassLeader() {
duty = "class monitor";
}
public ClassLeader(String duty, String name, String college) {
super(name, college); // 必須首行調用父類構造器
this.duty = duty;
}
@Override
public void print() {
super.print(); // 調用父類 print 方法
System.out.println("duty is " + duty);
}
public static void main(String[] args) {
ClassLeader leader = new ClassLeader("life", "linc", "shenyang");
leader.print();
}
}
this student name is linc
this student name is linc college is shenyang
name is: linc age is: 20 college is: shenyang
duty is life
base 關鍵字,功能等同於 Java 的 super。BaseClass::method())。this 用於當前類內部引用,super 用於子類訪問父類成員。掌握它們的調用規則(特別是構造器鏈中的位置限制)能有效避免繼承體系中的常見錯誤。