標籤:des friends 不可 構造方法 類的方法 please java學習 方法 成員
super 關鍵字與 this 類似,this 用來表示當前類的執行個體,super 用來表示父類。
super 可以用在子類中,通過點號(.)來擷取父類的成員變數和方法。super 也可以用在子類的子類中,Java 能自動向上層類追溯。
父類行為被調用,就好象該行為是本類的行為一樣,而且調用行為不必發生在父類中,它能自動向上層類追溯。
super 關鍵字的功能:
· 調用父類中聲明為 private 的變數。
· 點取已經覆蓋了的方法。
· 作為方法名表示父類構造方法。
調用隱藏變數和被覆蓋的方法
1. public class Demo{
2. public static void main(String[] args) {
3. Dog obj = new Dog();
4. obj.move();
5. }
6. }
7. class Animal{
8. private String desc = "Animals are human‘s good friends";
9. // 必須要聲明一個 getter 方法
10. public String getDesc() { return desc; }
11.
12. public void move(){
13. System.out.println("Animals can move");
14. }
15. }
16. class Dog extends Animal{
17. public void move(){
18. super.move(); // 調用父類的方法
19. System.out.println("Dogs can walk and run");
20. // 通過 getter 方法調用父類隱藏變數
21. System.out.println("Please remember: " + super.getDesc());
22. }
23. }
運行結果:
Animals can move
Dogs can walk and run
Please remember: Animals are human‘s good friends
move() 方法也可以定義在某些祖先類中,比如父類的父類,Java 具有追溯性,會一直向上找,直到找到該方法為止。
通過 super 調用父類的隱藏變數,必須要在父類中聲明 getter 方法,因為聲明為 private 的資料成員對子類是不可見的。
調用父類的構造方法
在許多情況下,使用預設構造方法來對父類對象進行初始化。當然也可以使用 super 來顯示調用父類的構造方法。
1. public class Demo{
2. public static void main(String[] args) {
3. Dog obj = new Dog("花花", 3);
4. obj.say();
5. }
6. }
7. class Animal{
8. String name;
9. public Animal(String name){
10. this.name = name;
11. }
12. }
13. class Dog extends Animal{
14. int age;
15. public Dog(String name, int age){
16. super(name);
17. this.age = age;
18. }
19.
20. public void say(){
21. System.out.println("我是一隻可愛的小狗,我的名字叫" + name + ",我" + age + "歲了");
22. }
23. }
運行結果:
我是一隻可愛的小狗,我的名字叫花花,我3歲了
注意:無論是 super() 還是 this(),都必須放在構造方法的第一行。
值得注意的是:
· 在構造方法中調用另一個構造方法,調用動作必須置於最起始的位置。
· 不能在構造方法以外的任何方法內調用構造方法。
· 在一個構造方法內只能調用一個構造方法。
如果編寫一個構造方法,既沒有調用 super() 也沒有調用 this(),編譯器會自動插入一個調用到父類構造方法中,而且不帶參數。(編輯:雷林鵬 來源:網路)
[Java學習] Java super關鍵字