为什么Java多态在我的示例中不起作用

我有以下4个Java案例:1


public 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;

    } 

}

2


public 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;

    }     

}

3


public 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;

    }     

}

4


public 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.0

pr1的面积= 24.0

cr1的面积= 6.0颜色=红色

POLY_MORPHISM 

r2的面积= 2.0

pr2的面积= 8.0

cr2的面积= 2.0颜色=透明***

为什么将cr2视为Rect(超类)并且具有“透明”颜色而不将其作为CRect(子类)具有“蓝色”颜色?


慕后森
浏览 358回答 3
3回答

江户川乱折腾

这是使用可见场的问题之一-您最终会使用它们...你已经有了一个color在外地都Rect和CRect。字段是不是多态的,所以当你使用cr2.color,使用宣布在该领域Rect,它始终设置为"transparent"。你的CRect类应该不会有自己的color领域-它应该提供颜色与父类的构造。一个矩形具有两个不同的color字段是没有意义的-它可以有borderColor和fillColor当然-但color太含糊了...

倚天杖

cr2.area()会打电话,CRect.area()但cr2.color会使用该字段Rect.color。您应该使用函数风格的getArea()和拥有CRect.getColor() { return color; },以及Rect.getColor() { return color; }

慕的地6264312

您应该super()在子类的构造函数中包含一个显式调用:public CRect(double w, double h ,String c) {    super(w, h);    width=w;    height=h;    color=c;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java