我正在使用 Java。我已经完成了所有可能的研究,但找不到问题的答案。此代码的某些部分不允许我更改,但仍能满足作业的要求。我正在与七个类(class)一起工作。 “Shape”类看起来像这样:
package homework6;
public abstract class Shape{
protected String name;
public String getname(){
return name;
}
abstract double getSurfaceArea();
}
我不允许更改此类的任何部分。其他类称为 Circle、Cylinder、Square、Geometric Shape 和主类。在每个构造函数中,我都被指示“将名称设置为对象的名称”。我对每个类(class)都采用了相同的方式,例如:
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());
}
表面积正确显示,但我不确定我需要做什么才能显示名称。我不能添加任何尚不存在的方法或构造函数:名称应该以某种方式从已经存在的构造函数中提取。
最佳答案
看看方法:
public String getname(){
你这样调用它:
s.getName()
与许多语言一样,Java 区分大小写。
我认为这只是库的一个拼写错误(它应该是getName
,但如果是getname
就使用那个)。
此外,在您的 Rectangle
构造函数中:
public Rectangle(){
length = 0;
width = 0;
name = "Rectangle";
}
您可以只使用this
来调用另一个构造函数。它只会使您的代码更简单并删除重复的功能。
public Rectangle() {
this(0, 0)
}
关于java - 基本的多态/继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30131357/