简体   繁体   中英

Using an interface method for an object of one data type in an array of a different data type? Java

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?

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();

为了使SideObjectdisplaySides()方法能够与GeometricFigure2实例一起使用,您需要修改GeometricFigure2以实现SidedObject

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM