加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

为什么java多态在我的例子中不起作用

发布时间:2020-12-14 05:37:43 所属栏目:Java 来源:网络整理
导读:我有这4个 java clases: 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() {
我有这4个 java clases:
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,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,"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,"Blue");
        System.out.println("area of cr2="+cr2.area()+"  color = "+cr2.color); 

    }
}

我得到了输出:

area of r1=6.0
area of pr1=24.0
area of cr1=6.0  color = RED
POLY_MORPHISM 
area of r2=2.0
area of pr2=8.0
area of cr2=2.0  color = transparent***

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

解决方法

这是使用可见字段的问题之一 – 您最终使用它们…

你在Rect和CRect中都有一个颜色字段.字段不是多态的,因此当您使用cr2.color时,它使用在Rect中声明的字段,该字段始终设置为“透明”.

您的CRect类不应该有自己的颜色字段 – 它应该为超类构造函数提供颜色.单个矩形有两个不同的颜色区域是没有意义的 – 它当然可以有borderColor和fillColor–但只是颜色太模糊了……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读