我有以下4個Java案例:1public class Rect { double width; double height; String color; public Rect( ) { width=0; height=0; color="transparent"; } public Rect( double w,double h) { width=w; height=h; color="transparent"; } double area() { return width*height; } }2public class PRect extends Rect{ double depth; public PRect(double w, double h ,double d) { width=w; height=h; depth=d; } double area() { return width*height*depth; } }3public class CRect extends Rect{ String color; public CRect(double w, double h ,String c) { width=w; height=h; color=c; } double area() { return width*height; } }4public class test { public test() { } public static void main(String[] args) { Rect r1=new Rect(2,3); System.out.println("area of r1="+r1.area()); PRect pr1=new PRect(2,3,4); System.out.println("area of pr1="+pr1.area()); CRect cr1=new CRect(2,3,"RED"); System.out.println("area of cr1="+cr1.area()+" color = "+cr1.color); System.out.println("\n POLY_MORPHISM "); Rect r2=new Rect(1,2); System.out.println("area of r2="+r2.area()); Rect pr2=new PRect(1,2,4); System.out.println("area of pr2="+pr2.area()); Rect cr2=new CRect(1,2,"Blue"); System.out.println("area of cr2="+cr2.area()+" color = "+cr2.color); }}我得到了輸出:r1的面積= 6.0pr1的面積= 24.0cr1的面積= 6.0顏色=紅色POLY_MORPHISM r2的面積= 2.0pr2的面積= 8.0cr2的面積= 2.0顏色=透明***為什么將cr2視為Rect(超類)并且具有“透明”顏色而不將其作為CRect(子類)具有“藍色”顏色?
3 回答

慕森卡
TA貢獻1806條經驗 獲得超8個贊
這是使用可見場的問題之一-您最終會使用它們...
你已經有了一個color在外地都Rect和CRect。字段是不是多態的,所以當你使用cr2.color,使用宣布在該領域Rect,它始終設置為"transparent"。
你的CRect類應該不會有自己的color領域-它應該提供顏色與父類的構造。一個矩形具有兩個不同的color字段是沒有意義的-它可以有borderColor和fillColor當然-但color太含糊了...

寶慕林4294392
TA貢獻2021條經驗 獲得超8個贊
cr2.area()會打電話,CRect.area()但cr2.color會使用該字段Rect.color。您應該使用函數風格的getArea()和擁有CRect.getColor() { return color; },以及Rect.getColor() { return color; }

www說
TA貢獻1775條經驗 獲得超8個贊
您應該super()在子類的構造函數中包含一個顯式調用:
public CRect(double w, double h ,String c) {
super(w, h);
width=w;
height=h;
color=c;
}
添加回答
舉報
0/150
提交
取消