2010年11月4日 星期四

[Java] super 的用法

ref: http://www.wretch.cc/blog/ez880/11180898

/**使用super保留字來呼叫父類別的成員
 *super通常有兩種用途  
 *第一種是讓子類別用來呼叫父類別的建構式(ConsTructor)
 *第二種是在子類別中透過super來呼叫父類別那些相同名稱的的成員
 *語法如下
 *super([引數串列])          //呼叫父類別的建構式
 *super.資料成員             //存取父類別的資料成員
 *super.方法成員([引數串列]) //呼叫父類別的方法成員
 */


class Student{
         private int weight,height;  //受保護的weight,height變數
         Student(){  // Student方法
            weight = 0; height=0;  //初始化weight height
         }
         Student(int weight,int height){ //Student方法 
            this.weight = weight;  //使用this保留字來參考目前的類別成員(解決名稱重複的方法)
            this.height = height;  //使用this保留字來辨認資料成員height等於參數height
         }
         void showData(){ //showData方法
            System.out.printf("身高:%s \t體重 %s",this.weight, this.height); //使用this保留字讓系統讀取參數weight height
         }
}

class SonStudent extends Student{//繼承Student父類別
         private int score;//受保護的score變數
                 SonStudent(){//SonStudent方法
                  super();  //呼叫Student父類別的Student()建構式
                  score=0;
         }
         SonStudent(int weight,int height,int score){  //SonStudent 
                  super(weight,height);  //呼叫Student父類別的Student(int weight,int height)方法
                  this.score = score; //使用this保留字讓系統辨認資料成員score等於參數score
         }
         void showData(){  //showData方法
                  super.showData();  //呼叫父類別的showData方法
                  System.out.print("\t成績:"+this.score);  
//使用this保留字來讓系統辨認資料成員score為SonStudent方法中的參數score }
}
public class SuperDemo {//SuperDemo類別
    public static void main(String[] args) { 
//宣告一個static靜態成員 無回傳型態(void) 並是(main)程式進入點     Student Peter= new Student(50,170);  //宣告Peter物件屬於Student並建立Peter物件 使用SonStudent(50,170)     Peter.showData();  //呼叫父類別的showData方法
     System.out.println("\n");
     SonStudent Lung = new SonStudent(65,164,99); //宣告Peter物件屬於Student並建立Peter物件
     Lung.showData(); //呼叫子類別的showData()方法
    }
  }

引用: Java2 完美的演譯 知城數位

6 則留言:

  1. 字的顏色跟網頁背景太相似
    導致閱讀困難,建議將背景改為白色...

    回覆刪除
  2. 烏漆媽黑的 有夠不好看 可以換成別的顏色嗎

    回覆刪除
  3. 烏漆媽黑的 有夠不好看 可以換成別的顏色嗎

    回覆刪除