1、this(參數):調用本類中另一種形成的構造函數(應該為構造函數中的第一條語句)
2 、 super(參數):調用父類中的某一個構造函數(應該為構造函數中的第一條語句)
3、this:它代表當前對象名(在程序中易產生二義性之處,應使用this來指明當前對象;如果函數的形參與類中的成員數據同名,這時需用this來指明成員變量名)
4、super: 它引用當前對象的直接父類中的成員(用來訪問直接父類中被隱藏的父類中成員數據或函數,基類與派生類中有相同成員定義時)
如:super.變量名
super.成員函數據名(實參)
應用實例:
class Person{
private String name;
private int age;
public Person(String name,int age){
this.setName(name);
this.setAge(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 print(){
System.out.print("姓名:"+this.getName()+",年齡:"+this.getAge());
}
}
class Student extends Person{
private String School;
public Student(String name,int age,String school){
super(name,age);
this.setSchool(school);
}
public String getSchool() {
return School;
}
public void setSchool(String school) {
School = school;
}
public void print(){
super.print();
System.out.println(",學校:"+this.School);
}
}
public class Demo01 {
public static void main(String[] args) {
Student stu=new Student("宋可",23,"唐山師范學院");
stu.print();
}
}
運行結果:
