在数组中调用类的方法 - Java

时间:2013-05-22 14:45:02

标签: java arrays class methods shape

我遇到了项目问题。

所以基本上我所拥有的是具有一些子类(ShapeRectangle,ShapeTriangle等)的类Shape。 在每个子类中,我得到了一个outputShape方法:     g.fillRect(getX(),getY(),getWidth(),getHeight());

在另一个类showShapes中,我得到了一个包含子类的数组。

我想通过数组运行该方法。

有什么办法吗?

编辑: showShapes中的数组是一个Shape []数组。

以下是ShapeRect的代码(抱歉,位是法语): import java.awt.Color; import java.awt.Graphics;

public class FormeRectangulaire extends Forme {
  public FormeRectangulaire(int x, int y, int width, int height){
    setX(x);
    setY(y);
    setWidth(width);
    setHeight(height);
    setColor(Color.RED);
  }

  public void afficherForme(Graphics g){
    g.setColor(getColor());
    g.fillRect(getX(), getY(), getWidth(), getHeight());
  }
}

这是形状:     import java.awt.Color;     import java.awt.Graphics;

public class Forme {

private int x;
private int y;
private int width;
private int height;
private Color color;

/*public void afficherForme(Graphics g){
    afficherForme(g);
}*/

public int getX() {
    return x;
}
public void setX(int x) {
    this.x = x;
}

public int getY() {
    return y;
}
public void setY(int y) {
    this.y = y;
}

public Color getColor(){
    return color;
}

public void setColor(Color color){
    this.color = color;
}

public int getWidth() {
    return width;
}
public void setWidth(int width) {
    this.width = width;
}

public int getHeight() {
    return height;
}
public void setHeight(int height) {
    this.height = height;
}

}

以下是我将每个类放在数组中的方法:

    public void creerArrayFormes(){
    String[][] donnes = getDatas();

    if(donnes[getDatasElement()][0].equals("CARRE") || donnes[getDatasElement()][0].equals("RECTANGLE")){
        FormeRectangulaire rect = new FormeRectangulaire(Integer.parseInt(donnes[getDatasElement()][1]),Integer.parseInt(donnes[getDatasElement()][2]),Integer.parseInt(donnes[getDatasElement()][3]),Integer.parseInt(donnes[getDatasElement()][4]));

        setFormes(rect, getDatasElement());
    }

}

2 个答案:

答案 0 :(得分:1)

您必须创建一个数组对象或 SuperClass List

List<Form> shapes = new ArrayList<Form>();
//List<Form> shapes = new ArrayList<>(); in JDK 7
shapes.add(new ShapeRectangle());
shapes.add(new ShapeTriangle());
//....

创建一个循环来获取对象:

  for(int i = 0; i<shapes.size();i++){
      Object obj = shapes.get(i);
      if(objinstanceof ShapeRectangle){
         ((ShapeRectangle)obj).fillRect(....);
      }
      else if(list.get(i)
    }

答案 1 :(得分:1)

我强烈建议将outputShape添加到Shape类。如果Shape是自然抽象的(不期望实际创建一个新的Shape()),它可以是抽象的。

如果你这样做,你可以迭代你的Shape []并为一个元素调用outputShape。这将调用outputShape的版本作为元素的实际类:

for(Shape s: shapes) {
  s.outputShape();
}