Why does Java polymorphism not work in my example

I have these four Java claims:

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

two

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

three

public class CRect extends Rect{ 
    String color;

    public CRect(double w,String c) {
        width=w;
        height=h;
        color=c;
    }

    double area()
    {
        return  width*height;
    }     
}

four

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

    }
}

I got the output:

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***

Why is CR2 considered a Rect (superclass) and a "transparent" color as a crect (subclass) with a "blue" color?

Solution

This is one of the problems with using visible fields – you end up using them

You have a color field in both rect and crect Fields are not polymorphic, so when you use CR2 Color, it uses the field declared in rect, which is always set to transparent

Your crect class should not have its own color field - it should provide color for the superclass constructor It doesn't make sense for a single rectangle to have two different color areas - of course it can have bordercolor and fillcolor - but the color is too blurred

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>