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:
GeometricFigure2
implement your SidedObject
interface. SidedObject[]
instead of GeometricFigure2[]
. SidedObject
: ((SidedObject) geoRef[i]).displaySides();
为了使SideObject
的displaySides()
方法能够与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.