Java重写
我有两个变量的超类矩形和一个变量的子类正方形。我使用类Square来继承getArea()方法并将其很好地覆盖。Eclipse编辑器在我的SQUARE类中给了我一个错误,“super(宽度,长度);”。长度变量有一个错误,可以通过在矩形类中将其设置为静态来修复,我想这不是我想要的。我的家庭作业要求SQUARE类有一个构造函数,其中有一个变量可以自己相乘。我的代码中的逻辑错误是什么
public class Rectangle
{
double width, length;
Rectangle(double width, double length)
{
this.width = width;
this.length = length;
}
double getArea()
{
double area = width * length;
return area;
}
void show()
{
System.out.println("Rectangle's width and length are: " + width + ", " + length);
System.out.println("Rectangle's area is: " + getArea());
System.out.println();
}
}
public class Square extends Rectangle
{
double width, length;
Square(double width)
{
super(width, length);
this.width = width;
}
double getArea()
{
double area = width * width;
return area;
}
void show()
{
System.out.println("Square's width is: " + width) ;
System.out.println("Square's area is: " + getArea());
}
}
public class ShapesAPP
{
public static void main(String[] args)
{
Rectangle shape1 = new Rectangle(5, 2);
Square shape2 = new Square(5);
shape1.show( );
shape2.show( );
}
}
# 1 楼答案
你应该有这样的构造函数:
此外,还应该在Square类中删除以下行:
double width, length;
# 2 楼答案
应该是:
A
Square
是一个所有边长度相等的矩形出现错误是因为您试图使用尚未初始化的
length
此外,在
Square
中不需要有width
和length
成员。在基类中已经有了它们。因此,更好的修订版本应该是: