I have Super class RECTANGLE with 2 variables and a Child class SQUARE with 1 variable. I am using class Square to inherit the getArea() method and overide it fine. Eclipse editor gives me an error in my SQUARE class, “super(width, length);”. LENGTH variable has an error that can be fixed with making it static in the RECTANGLE class, that’s not what I desire I guess. My homework requires that class SQUARE has a constructor with 1 variable to multiply by itself. What is the logical error in my code?
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( );
}
}
It should be:
A
Squareis a rectangle with all sides of equal length.You get the error because you’re attempting to use
lengthwhich wasn’t yet initialized.Also, you needn’t have members
widthandlengthinSquare. You already have them in the base class. So a better revised version would be: