看板 java 關於我們 聯絡資訊
abstract class CShape{ protected String color; public void setColor(String str){ color=str; } } class CRectangle extends CShape{ protected int width,height; public CRectangle(int w, int h){ width=w; height=h; } public void show(){ System.out.print("color="+color); System.out.println(", area="+width*height); } } class CCircle extends CShape{ protected double radius; public CCircle(double r){ radius=r; } public void show(){ System.out.print("color="+color); System.out.println(", area="+3.14*radius*radius); } } public class ex11_4{ public static void main(String[] args){ CRectangle rect = new CRectangle(5,10); //當建立此建構元時,為何不用呼叫父類別(抽象類別的建構元)... //能正確執行...?? rect.setColor("Yellow"); rect.show(); CCircle cir = new CCircle(2.0); cir.setColor("Green"); cir.show(); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.46.120.179
lachtchlee:不清礎所問 但建議CShape rect= new CRectangle(5,10); 08/23 23:45
No:他CShape沒有show() method,改CShape rect就掰了 08/23 23:53
lachtchlee:是的 沒仔細看 08/23 23:55
No:這code父類別建構元沒東西,不呼叫沒影響,通常呼叫是要初始化 08/23 23:58
spiderman007:當執行到CRectangle(int ,int )建構元時... 08/24 00:01
spiderman007:沒東西...了解了...謝謝.. 08/24 00:02
adrianshum:子類別 ctor 之前其實會自動跑父類別的 ctor 08/24 08:53
No:是的,會自動呼叫~ 08/25 02:33
shaopin:呼叫的是default, 若有想要呼叫有引數的 還是要explicit 08/25 13:53
shaopin:呼叫父類的ctor 08/25 13:55
sk8er411:抽象類別不是不能直接呼叫嗎? 09/06 09:49