亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么Java多態在我的示例中不起作用

為什么Java多態在我的示例中不起作用

森林海 2019-10-12 10:42:02
我有以下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太含糊了...


查看完整回答
反對 回復 2019-10-12
?
寶慕林4294392

TA貢獻2021條經驗 獲得超8個贊

cr2.area()會打電話,CRect.area()但cr2.color會使用該字段Rect.color。您應該使用函數風格的getArea()和擁有CRect.getColor() { return color; },以及Rect.getColor() { return color; }


查看完整回答
反對 回復 2019-10-12
?
www說

TA貢獻1775條經驗 獲得超8個贊

您應該super()在子類的構造函數中包含一個顯式調用:


public CRect(double w, double h ,String c) {

    super(w, h);

    width=w;

    height=h;

    color=c;

}


查看完整回答
反對 回復 2019-10-12
  • 3 回答
  • 0 關注
  • 328 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號