本範例展示類別繼承與方法覆寫。基底類別 tree 定義樹的根、幹、枝、葉屬性與行為;子類別 osier(柳樹)繼承 tree,覆寫 leaf() 增加葉片形狀,並擴充 flower() 方法。
class tree {
public void root() {
String sSite = "土壤中";
String sFunction = "吸收養份";
print("位置:" + sSite);
print("功能:" + sFunction);
}
public void bolo() {
String sSite = "地面";
String sFunction = "傳遞養份";
print("位置:" + sSite);
print("功能:" + sFunction);
}
public void branch() {
String sSite = "樹幹上";
String sFunction = "傳遞養份";
print("位置:" + sSite);
print("功能:" + sFunction);
}
public void leaf() {
String sSite = "樹梢";
String sFunction = "光合作用";
String sColor = "綠色";
print("位置:" + sSite);
print("功能:" + sFunction);
print("顏色:" + sColor);
}
public void print(Object oPara) { System.out.println(oPara); }
public static void main(String[] arges) {
tree t = new tree();
t.print("描述一棵樹:");
t.print("樹根:"); t.root();
t.print("樹幹:"); t.bolo();
t.print("樹枝:"); t.branch();
t.print("樹葉:"); t.leaf();
}
}
class osier extends tree {
public void leaf() {
super.leaf();
String sShape = "長形";
super.print("形狀:" + sShape);
}
public void flower() {
print("哈哈,柳樹沒有花!!");
}
public static void main(String[] args) {
osier o = new osier();
o.print("柳樹樹根:"); o.root();
o.print("柳樹樹幹:"); o.bolo();
o.print("柳樹樹枝:"); o.branch();
o.print("柳樹樹葉:"); o.leaf();
o.print("柳樹花:"); o.flower();
}
}
執行 osier.main() 將輸出柳樹各部位特徵,展現繼承、覆寫與 super 調用父類別方法的用法。