-1

2 つの変数を持つスーパー クラス RECTANGLE と、1 つの変数を持つ子クラス 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( );
}

}
4

2 に答える 2

4

次のようなコンストラクタが必要です。

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

また、Square クラスの次の行を削除する必要があります。double width, length;

于 2012-05-28T23:18:56.730 に答える
1

そのはず:

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

ASquareはすべての辺の長さが等しい長方形です。

lengthまだ初期化されていないものを使用しようとしているため、エラーが発生します。

widthまた、 membersとlengthinは必要ありませんSquare。それらは基本クラスに既にあります。したがって、より良い改訂版は次のようになります。

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

}
于 2012-05-28T23:18:46.547 に答える