我有一个抽象类,TwoDPolygon。
abstract class TwoDPolygon
{
double width, height;
String name;
public TwoDPolygon()
{
width = 0;
height = 0;
name = null;
}
public TwoDPolygon(double width, double height, String name)
{
this.width = width;
this. height = height;
this.name = name;
}
public TwoDPolygon(double equalWidthHeight, String name)
{
width = equalWidthHeight;
height = equalWidthHeight;
name = name;
}
public String getName()
{
return name;
}
abstract double area();
}
一个子类 Triangle,它扩展了 TwoDPolygon。
public class Triangle extends TwoDPolygon
{
String status;
public Triangle()
{
super();
}
public Triangle(String status, double width, double height)
{
this.status = status;
this.width = width;
this.height = height;
}
public Triangle(double size)
{
}
public String getStatus()
{
if ("filled".equals(status))
status = "filled";
if ("notFilled".equals(status))
status = "notFilled";
return status;
}
double area()
{
return (1/2)*(width)*(height);
}
}
还有一个主要方法,这是提供给我的。另外两个类是我自己编写的,给出了主要方法和一些说明。
public class Ex2Driver
{
public static void main(String[] args)
{
TwoDPolygon polygons[] = new TwoDPolygon[3];
polygons[0] = new Triangle("filled", 8.5, 12.0);
polygons[1] = new Triangle("not Filled", 6.5, 7.5);
polygons[2] = new Triangle(7.0);
for (int i=0; i<polygons.length; i++)
{
System.out.println("Object is " + polygons[i].getName());
System.out.println("Triangle " + polygons[i].getStatus());
System.out.println("Area is " + polygons[i].area());
}
}
}
我意识到 Triangle 类中的第三个构造函数是空的。我知道它应该在那里,根据说明,但我不知道要在里面放什么。不管怎样,我从驱动程序类中收到了“找不到符号”错误
System.out.println("Triangle " + polygons[i].getStatus());
最佳答案
因为polygons[]的类型是TwoDPolygonTwoDPolygongonys[] = new TwoDPolygon[3];
,所以它在TwoDPolygon的类声明中查找方法getStatus(),而不是Triangle,甚至尽管元素被实例化为三角形。
您有多种选择来解决此问题:
将声明更改为三角形
三角形多边形[] = new Triangle[3];
将 getStatus 方法移至 TwoDPolygon
在每个循环中将对象转换为 Triangle
System.out.println("三角形"+ ((Triangle)polygons[i]).getStatus());
关于java - 为什么我会收到以下错误以及空构造函数中应该有什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29190590/