指向Java中不同类实例的对象数组

时间:2013-02-24 05:50:19

标签: java arrays object

我有一个类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个球体。

2 个答案:

答案 0 :(得分: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.
    }
}

答案 1 :(得分: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());
    }
}