在解釋 this 和 super 的區別之前先說一下方法的重寫 (Override) 和重載 (OverLoad)
- 方法的重寫 (Override):在子類中,出現和父類一模一樣方法聲明的現象
public class Person
{
private String name;
private int age;
private String hobby;
public void show()
{
System.out.println("姓名:" + name + " 年齡:" + age + " 愛好:" + hobby);
}
}
public class Student extends Person
{
private int score;
public void show()
{
System.out.println("姓名:" + name + " 年齡:" + age + " 愛好:" + hobby + " 分數:" + score);
}
}
在子類 Student 類中聲明瞭一個和父類 Person 類相同的 show() 方法,因此構成了方法的重寫
- 方法的重載 (OverLoad):在本類中,出現方法名相同,參數列表不同的現象(跟返回值無關)
public class Student extends Person
{
private int score;
public void show()
{
System.out.println("姓名:" + name + " 年齡:" + age + " 愛好:" + hobby + " 分數:" + score);
}
public void show(int score)
{
System.out.println("姓名:" + name + " 年齡:" + age + " 愛好:" + hobby + " 分數:" + score);
}
}
在 Student 類中存在兩個方法名同爲 show 的方法聲明,但是兩個方法參數列表不同,因此構成了方法的重載
this 和 super
- this:本類數據的引用
this.變量名 調用本類的成員變量
this(..) 調用本類的構造方法
this.method(..) 調用本類的成員方法
public class Person
{
private String name;
private int age;
private String hobby;
public int num = 10;
public Person()
{
}
public Person(String name, int age)
{
this.name = name; //調用本類的成員變量
this.age = age;
}
public Person(String name, int age, String hobby)
{
this(name, age); //調用本類帶兩個參數的構造方法
this.hobby = hobby;
}
public void show()
{
System.out.prinltn("Person");
}
}
- super:代表存儲空間的標識(可以理解爲父類的引用)
super.變量名 調用父類的成員變量
super(..) 調用父類的構造函數
super.method(..) 調用父類的成員方法
public class Person
{
private String name;
private int age;
private String hobby;
public int num = 10;
public Person()
{
}
public Person(String name, int age)
{
this.name = name; //調用本類的成員變量
this.age = age;
}
public Person(String name, int age, String hobby)
{
this(name, age); //調用本類帶兩個參數的構造方法
this.hobby = hobby;
}
public void show()
{
System.out.prinltn("Person");
}
}
public class Student extends Person
{
private int score;
private int num = 20;
public Student(String name, int age, String hobby)
{
super(name, age, hobby); //調用父類的帶參構造
}
public void method()
{
int num = 30;
System.out.println("Person的num" + super.num);//調用父類Person成員變量num = 10
System.out.println("Student的num" + this.num);//調用本類Student成員變量num = 20
System.out.println("method的num" + num);//調用method的局部變量num = 30
}
public void show()
{
super.show();//調用父類Person的show()方法
System.out.prinltn("Person");
}
}
注意:
1、在子類的構造方法中會默認調用父類的無參構造方法,這是因爲子類繼承了父類的成員,而且可能會用到父類的成員,所以需要調用父類無參構造對成員進行初始化。
2、子類調用父類構造函數時並不會創建父類對象,所以此時構造函數中的 this 實際上子類對象
3、this(..) 和super (..) 必須出現在第一條語句