6

私はこれらの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(サブクラス)と見なさないのですか?

4

3 に答える 3

13

これは可視フィールドを使用する際の問題の 1 つです。

と の両方にフィーcolor​​ルドがRectありCRectます。フィールドは多態的ではないため、 を使用するcr2.colorと、 で宣言されたフィールドが使用されRect常にに設定され"transparent"ます。

クラスは独自のフィールドを持つCRectべきではありませcolor。スーパークラス コンストラクターに色を提供する必要があります。1 つの長方形が 2 つの異なるcolorフィールドを持つことは意味がありません。もちろん、borderColorとを持つこともできますが、あいまいすぎます...fillColorcolor

于 2012-12-06T16:34:48.653 に答える
0

cr2.area()を呼び出しますCRect.area()cr2.color、フィールドを使用しますRect.color。関数スタイル getArea() を使用する必要がありますCRect.getColor() { return color; }Rect.getColor() { return color; }

于 2012-12-06T16:40:55.203 に答える
0

super()サブクラスのコンストラクターに明示的な呼び出しを含める必要があります。

public CRect(double w, double h ,String c) {
    super(w, h);
    width=w;
    height=h;
    color=c;
}
于 2012-12-06T16:37:32.710 に答える