0

I am trying to create an abstract class (Shape), and three subclasses (Square, Circle, Triangle), each having no fields and one void method -- "drawShape" -- that draws each shape in asterisks. I am then supposed to, in my main method, create an array of each Shape subclass object and loop through to call their drawShape methods. Unfortunately, I keep getting the error: File: C:\Users\Robert\Demo.java [line: 13] Error: Syntax error on token(s), misplaced construct(s)

My question is how can I create these Shape objects and also how can I implement a loop to call their drawShape methods in an array of these objects.

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 Answers3

1

Like this:

Shape[] shapes = new Shape[] {triangle, circle, square};
breakline
  • 5,006
  • 5
  • 35
  • 70
0

This: Shape[] shapes = new Shape{triangle, circle, square}; needs to become: Shape[] shapes = new Shape[] {triangle, circle, square};

An array object is an Iterable in Java. This means that you can use the modified for loop to go through it:

for(Shape shape : shapes)
    shape.drawShape();
npinti
  • 50,175
  • 5
  • 67
  • 92
-1

Use it like below :

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);
Emre Savcı
  • 2,628
  • 1
  • 13
  • 24