-1

我有一堂几何课。在另一个类中,我想创建一个 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 回答