第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

為什么Java多態(tài)在我的示例中不起作用

為什么Java多態(tài)在我的示例中不起作用

森林海 2019-10-12 10:42:02
我有以下4個(gè)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(子類)具有“藍(lán)色”顏色?
查看完整描述

3 回答

?
慕森卡

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個(gè)贊

這是使用可見場(chǎng)的問題之一-您最終會(huì)使用它們...


你已經(jīng)有了一個(gè)color在外地都Rect和CRect。字段是不是多態(tài)的,所以當(dāng)你使用cr2.color,使用宣布在該領(lǐng)域Rect,它始終設(shè)置為"transparent"。


你的CRect類應(yīng)該不會(huì)有自己的color領(lǐng)域-它應(yīng)該提供顏色與父類的構(gòu)造。一個(gè)矩形具有兩個(gè)不同的color字段是沒有意義的-它可以有borderColor和fillColor當(dāng)然-但color太含糊了...


查看完整回答
反對(duì) 回復(fù) 2019-10-12
?
寶慕林4294392

TA貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊

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


查看完整回答
反對(duì) 回復(fù) 2019-10-12
?
www說

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊

您應(yīng)該super()在子類的構(gòu)造函數(shù)中包含一個(gè)顯式調(diào)用:


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

    super(w, h);

    width=w;

    height=h;

    color=c;

}


查看完整回答
反對(duì) 回復(fù) 2019-10-12
  • 3 回答
  • 0 關(guān)注
  • 327 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)