- 讓子類別呼叫父類別的建構子Constructor
- 讓子類別呼叫父類別的方法methods
語法通常有幾種寫法:
- suepr()
- super([引數串列]) //呼叫父類別的建構式
- super.資料成員 //存取父類別的資料成員
- super.方法成員([引數串列]) //呼叫父類別的方法成員
例1:
package nb_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 NB_Super {
public static void main(String[] args) {
System.out.println("\n");
SonStudent Lung = new SonStudent(65,164,99); //宣告Peter物件屬於Student並建立Peter物件
Lung.showData(); //呼叫子類別的showData()方法
}
}
run: 身高:65 體重 164 成績:99例2,如果這樣寫,會錯:
class Father{
String my_son_Name;
Father(String name){//此父類別建構子需要傳入 字串參數
my_son_Name = name;
}
public void getName(){
System.out.println("我兒子叫做:"+my_son_Name);
}
}
public class Son extends Father{
Son(){
}
public static void main(String[] args) {
Son son = new Son();
son.getName();
}
}
要這樣寫,子類別自己的建構子裡面再加一個super來呼叫父類別的建構子:
class Father{
String my_son_Name;
Father(String name){
my_son_Name = name;
}
public void getName(){
System.out.println("我兒子叫做:"+my_son_Name);
}
}
public class Son extends Father{
Son(){
super("Andy");
}
public static void main(String[] args) {
Son son = new Son();
son.getName();
}
}
執行結果 : 我的兒子叫做:Andy參考資料:
http://pics.ee/p0x
[Java] super 的用法
沒有留言:
張貼留言