我正在使用Java。我已经做了所有可能的研究,但是我找不到我的问题的答案。这些代码的某些部分我不允许改变,仍然满足作业的要求。我正在和七个班级一起工作。 “Shape”类看起来像这样:
package homework6;
public abstract class Shape{
protected String name;
public String getname(){
return name;
}
abstract double getSurfaceArea();
}
我不允许更改此课程的任何部分。其他类称为圆形,圆柱形,方形,几何形状和主类。在每个构造函数中,我被指示“将名称设置为等于对象的名称”。我为每个班级做了同样的事情,EG:
package homework6;
public class Rectangle extends Shape{
public double length;
public double width;
public Rectangle(){
length = 0;
width = 0;
name = "Rectangle";
}
public Rectangle(double l, double w){
length = l;
width = w;
name = "Rectangle";
}
double getSurfaceArea(){
return length*width;
}
}
这是问题所在。在我的主要课程中,我也无法改变,有一些测试代码。除了“名称”部分之外,我程序中的所有内容都能正常工作。在下面的代码中,“getName”带有红色下划线,错误是“找不到符号”。我尝试过使用'super'关键字,但我无法使其正常工作。我已经研究了好几天了,我看过无数的YouTube视频,但我无法弄清楚这一点。
public static void main(String args []){
Shape list_of_shapes[] = new Shape[10];
list_of_shapes[0] = new Circle();
list_of_shapes[1] = new Circle(1.5);
list_of_shapes[2] = new Rectangle();
list_of_shapes[3] = new Rectangle(3.5, 2);
list_of_shapes[4] = new Square();
list_of_shapes[5] = new Square(4.5);
list_of_shapes[6] = new Cylinder();
list_of_shapes[7] = new Cylinder(1.5, 2);
boolean skipLine = false;
for(Shape s : list_of_shapes)
{
if(s instanceof Circle && !(s instanceof Cylinder))
{
System.out.println("Object of class " + s.getName() + " with radius = " + ((Circle)(s)).radius + ",");
System.out.println("has an area of " + s.getSurfaceArea());
}
else if (s instanceof Rectangle && !(s instanceof Square))
{
System.out.println("Object of class " + s.getName() + " with length = " + ((Rectangle)(s)).length + " and width = " + ((Rectangle)(s)).width + ",");
System.out.println("has an area of " + s.getSurfaceArea());
}
else if (s instanceof Square)
{
System.out.println("Object of class " + s.getName() + " with length = " + ((Square)(s)).length + " and width = " + ((Square)(s)).width + ",");
System.out.println("has an area of " + s.getSurfaceArea());
}
else if (s instanceof Cylinder)
{
System.out.println("Object of class " + s.getName() + " with radius = " + ((Cylinder)(s)).radius + " and height = " + ((Cylinder)(s)).height + ",");
System.out.print("has an area of " + s.getSurfaceArea());
System.out.println(" and a volume of " + ((Cylinder)(s)).getVolume());
}
表面区域显示正确,但我不确定我需要做什么才能显示名称。我不能添加任何尚未存在的方法或构造函数:应该从已经存在的构造函数中提取名称。
答案 0 :(得分:4)
看一下方法:
public String getname(){
你这样称呼它:
s.getName()
Java与许多语言一样,具有一定的敏感性。
我认为这只是图书馆的一个错字( 应该getName
,但如果是getname
则只使用它。)
另外,在Rectangle
构造函数中:
public Rectangle(){
length = 0;
width = 0;
name = "Rectangle";
}
您可以使用this
来调用其他构造函数。它只是使您的代码更简单,并删除重复的功能。
public Rectangle() {
this(0, 0)
}