-1

クラス Geometry があります。別のクラスで、Geometry のインスタンスの配列を作成し、それらを参照したいと考えています。

class Geometry {

    private static int edges[];
    private static int vertices[];
    private static sphere();
    private static circle();  
}

class Example {

    Geometry [] Shape = new Geometry [5];
    public draw(){
        Shape[0] = new Geometry();
        Shape[1] = new Geometry();
        Shape[0].circle();
        Shape[1].sphere();

        <code to draw shape for Shape[i]>
    }
}

Sphere()Circle()エッジと頂点を異なる方法で初期化します。Shape[0] にはエッジと頂点に円の値が割り当てられ、Shape[1] には球体の値が割り当てられます。描画関数で各オブジェクトを反復処理すると、現在行っているように 2 つの球ではなく、円を描画してから球を描画する必要があります。

4

2 に答える 2

1

単一のクラスがあり、仮想関数はありません。したがって、これは実際にはオブジェクト指向のコードではありません。代わりに、次のようにしてみてください。

abstract class Geometry {
    private int edges[];
    private int vertices[];
    abstract void draw();
}

class Circle extends Geometry {
    void draw() {
       // Code to draw a circle here.
    }
}

class Sphere extends Geometry {
    void draw() {
       // Code to draw a shere here.
    }
}

class Example {

    Geometry [] shape = new Geometry [5];
    public draw() {
        shape[0] = new Circle();
        shape[1] = new Sphere();
        shape[0].draw(); // Will draw a circle.
        shape[1].draw(); // Will draw a sphere.
    }
}

この例では、関数 Geometry.draw() は空ですが、そこに何かを配置したり、サブクラスからこの関数を呼び出したりする可能性は十分にあります。

class Geometry {
    ...
    draw() { DoSomethingUseful(); }
}

class Circle extends Geometry {
    draw() {
       super.draw();
       // Remaining of the code to draw a circle here.
    }
}
于 2013-02-24T08:04:47.103 に答える
0

を使用する必要がありますPolymorphism

abstract class Geometry {

    private int edges[];
    private int vertices[];
    abstract void setdata();//Geometry class won't define this method, the classes deriving it must define it
    abstract void paintShape(Graphics graphics);//Geometry class won't define this method, the classes deriving it must define it  
}
class Circle extends Geometry
{
    public void paintShape(Graphics graphics)
    {
       //code to paint the circle
    }
    public void setdata()
    {
       //code to set the vertices and edges for a circle
    }
}
class Sphere extends Geometry
{
    public void paintShape(Graphics graphics)
    {
       //code to paint the sphere
    }
    public void setdata()
    {
       //code to set the vertices and edges for a sphere
    }
}

私のコメントは、あなたが必要とするかもしれないほぼすべての説明を提供します。
そして、あなたがこれらを描きたい間。

class Example {

    Geometry [] Shape = new Geometry [5];
    public draw(){
        Shape[0] = new Circle();
        Shape[1] = new Shape();
        Shape[0].setdata();
        Shape[1].setdata();

        //code to draw shape for Shape[i]
        Shape[0].draw(panel.getGraphics());
        Shape[1].draw(panel.getGraphics());
    }
}
于 2013-02-24T09:00:14.757 に答える