java - 为什么我会收到以下错误以及空构造函数中应该有什么?

标签 java inheritance constructor compiler-errors abstract-class

我有一个抽象类,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,甚至尽管元素被实例化为三角形。

您有多种选择来解决此问题:

  1. 将声明更改为三角形

    三角形多边形[] = new Triangle[3];

  2. 将 getStatus 方法移至 TwoDPolygon

  3. 在每个循环中将对象转换为 Triangle

    System.out.println("三角形"+ ((Triangle)polygons[i]).getStatus());

关于java - 为什么我会收到以下错误以及空构造函数中应该有什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29190590/

相关文章:

java - 无法执行 Selenium 异步脚本

c# - 当我真的需要继承两个类时如何处理CS1721?

c++ - 指向虚类的指针

c++ - 为什么不调用私有(private)成员的默认构造函数?

scala - 如何废弃 scala 类构造的样板?

java - 500-内部服务错误-使用 eQSL

Java StreamTokenizer 在 @ 符号处拆分电子邮件地址

java - 从主类访问时服务变量为空

c++ - 非虚拟成员的虚拟和继承成本?

asp.net - 处理 ASP.NET MVC Controller 构造函数中发生的异常