家庭作业Java Overriding

时间:2012-05-28 23:15:21

标签: java

我有2个变量的超类RECTANGLE和1个变量的Child类SQUARE。我正在使用类Square来继承getArea()方法并且覆盖它很好。 Eclipse编辑器在我的SQUARE类中给出了一个错误,“super(width,length);”。 LENGTH变量有一个错误,可以通过在RECTANGLE类中使其静态来修复,这不是我想要的。我的作业要求类SQUARE有一个带有1个变量的构造函数来自行相乘。我的代码中的逻辑错误是什么?

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( );
}

}

2 个答案:

答案 0 :(得分:4)

你应该有这样的构造函数:

Square(double width) 
{
    super(width, width);
}

此外,您应该删除Square类中的以下行:double width, length;

答案 1 :(得分:1)

应该是:

Square(double width) 
{
    super(width, width);
    //this.width = width;
}

Square是一个长度相等的矩形。

您收到错误是因为您尝试使用尚未初始化的length

此外,您无需在width中拥有成员lengthSquare。你已经在基类中拥有它们了。因此,更好的修订版本将是:

public class Square extends Rectangle
{
    Square(double width) 
    {
        super(width, length);
    }

    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());
    }

}