简体   繁体   English

对不同数据类型的数组中一种数据类型的对象使用接口方法吗? Java的

[英]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 . 所以我的问题是我有一个名为GeometricFigure2的类,其中包含widthheight等字段。 I have an interface called SidedObject which holds a method to display how many sides a figure has 我有一个名为SidedObject的接口,该接口包含一种方法来显示图形有多少侧

public interface SidedObject
{
    public void displaySides();
}

I have two subclasses called Square2 and Triangle2 which extend GeometricFigure2 and implement SidedObject . 我有两个名为Square2Triangle2子类,它们扩展了GeometricFigure2并实现SidedObject Both classes contain the displaySides() method which looks like: 这两个类都包含displaySides()方法,如下所示:

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

Finally I have a class called UseGeometricFigure2 which uses both subclasses. 最后,我有一个名为UseGeometricFigure2的类,它同时使用了两个子类。 I create an array with a type of GeometricFigure2 which is used to hold two Square2 objects and two Triangle2 objects: 我创建了一个类型为GeometricFigure2的数组,该数组用于容纳两个Square2对象和两个Triangle2对象:

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循环以遍历数组,并为数组中的每个对象调用displaySides()方法:

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. 它正在GeometricFigure2类(它是数组类型displaySides()中寻找displaySides() How do I correctly call the displaySides() method in this setup? 如何在此设置中正确调用displaySides()方法?

You have three choices: 您有三种选择:

  1. Have GeometricFigure2 implement your SidedObject interface. GeometricFigure2实现您的SidedObject接口。
  2. Declare your array as type SidedObject[] instead of GeometricFigure2[] . 将您的数组声明为SidedObject[]而不是GeometricFigure2[]
  3. Cast your array variables to SidedObject : 将数组变量转换为SidedObject
    ((SidedObject) geoRef[i]).displaySides();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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