为没有字段的类创建构造函数

时间:2018-08-06 09:55:02

标签: java arrays inheritance constructor

我正在尝试创建一个抽象类(Shape)和三个子类(Square,Circle,Triangle),每个子类都没有字段,并且有一个空方法(“ drawShape”)-用星号绘制每个形状。然后,应该在我的main方法中,为每个Shape子类对象创建一个数组,并循环调用其drawShape方法。不幸的是,我不断收到错误消息:File: C:\Users\Robert\Demo.java [line: 13] Error: Syntax error on token(s), misplaced construct(s)

我的问题是如何创建这些Shape对象,以及如何实现循环以在这些对象的数组中调用其drawShape方法。

public abstract class Shape
{
  public abstract void drawShape();
}

public class Square extends Shape
{
  @Override
  public void drawShape()
  {
    System.out.println("****\n" + "*  *\n*  *\n****");
  }
}

public class Circle extends Shape
{
  @Override
  public void drawShape()
  {
    System.out.println("   " + "*" + "\n  " + "* *" + "\n " + 
                       "*   *" + "\n  " + "* *" + "\n   " + "*");
  }
    }

public class Triangle extends Shape
{
  @Override
  public void drawShape()
  {
    System.out.println("   " + "*" + "   " +
                       "\n  " + "* *" + "  " + 
                       "\n " + "***" + " ");
  }
}

public class Demo
{
  public static void main(String[] args)
  {
    Triangle triangle = new Triangle();
    Circle circle = new Circle();
    Square square = new Square();
    Shape[] shapes = new Shape{triangle, circle, square};
    //How can I properly create this array^
    //How can I loop through the array to call each objects drawShape method

  }
}

3 个答案:

答案 0 :(得分:1)

赞:

Shape[] shapes = new Shape[] {triangle, circle, square};

答案 1 :(得分:0)

此:Shape[] shapes = new Shape{triangle, circle, square};必须成为:Shape[] shapes = new Shape[] {triangle, circle, square};

数组对象是Java中的Iterable。这意味着您可以使用经过修改的for循环进行遍历:

for(Shape shape : shapes)
    shape.drawShape();

答案 2 :(得分:-1)

按如下所示使用它:

Shape triangle = new Triangle();
Shape circle = new Circle();
Shape square = new Square();

Shape[] shapes = new Shape[] {triangle, circle, square};
Arrays.stream(shapes).forEach(Shape::drawShape);