1

So my problem is that I have a class called GeometricFigure2 which holds fields such as width and height. I have an interface called SidedObject which holds a method to display how many sides a figure has

public interface SidedObject
{
    public void displaySides();
}

I have two subclasses called Square2 and Triangle2 which extend GeometricFigure2 and implement SidedObject. Both classes contain the displaySides() method which looks like:

public void displaySides()
{
   System.out.println("The square has 4 sides.");
}

Finally I have a class called UseGeometricFigure2 which uses both subclasses. I create an array with a type of GeometricFigure2 which is used to hold two Square2 objects and two Triangle2 objects:

GeometricFigure2[] geoRef = new GeometricFigure2[4];
    geoRef[0] = new Square2();
    geoRef[1] = new Square2();
    geoRef[2] = new Triangle2();
    geoRef[3] = new Triangle2();

I then create a for loop to iterate through the array and call the displaySides() method for each object in the array:

for(int i=0; i<4; i++)
{
    geoRef[i].displaySides();
}

The problem is when I try to compile it gives me a "Cannot find symbol" error. It is looking for displaySides() in the GeometricFigure2 class which is the array type. How do I correctly call the displaySides() method in this setup?

2 Answers 2

1

You have three choices:

  1. Have GeometricFigure2 implement your SidedObject interface.
  2. Declare your array as type SidedObject[] instead of GeometricFigure2[].
  3. Cast your array variables to SidedObject:
    ((SidedObject) geoRef[i]).displaySides();
Sign up to request clarification or add additional context in comments.

1 Comment

The first option works best for me as I have other methods in the GeometricFigure2 class. Thank you!
0

For the displaySides() method from SideObject to work with instances of GeometricFigure2 you would need to modify GeometricFigure2 to implement SidedObject.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.