[英]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
的类,其中包含width
和height
等字段。 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
. 我有两个名为
Square2
和Triangle2
子类,它们扩展了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: 您有三种选择:
GeometricFigure2
implement your SidedObject
interface. GeometricFigure2
实现您的SidedObject
接口。 SidedObject[]
instead of GeometricFigure2[]
. SidedObject[]
而不是GeometricFigure2[]
。 SidedObject
: SidedObject
: ((SidedObject) geoRef[i]).displaySides();
为了使SideObject
的displaySides()
方法能够与GeometricFigure2
实例一起使用,您需要修改GeometricFigure2
以实现SidedObject
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.