shawn edward
shawn edward

Reputation: 149

object interaction: Calculation on geometric shape

So basically I have this question: 1)Square, a subclass of Rectangle, containing a constructor(with a parameter for the length of a side) and methods that invoke the methods of the Rectangle class to determine the perimeter and area of a square.

So far I have this for the square class

class sqaure extends rectangle
{
  public Square(double size)
 {
   super(size, size)
 }
}

and this for the rectangle class

class rectangle extends Shape
{
  private double length; 
  private double width; 

  public rectangle (double length, double width)
  {
    this.length = length; 
    this.width = width;
  }
  double area()
  {
    return length * width;
  }
  double perimeter()
  {
    return 2.0 * (width + length);
  }
}

I need help on the part where it says I need to invoke the method of the rectangle class to determine the perimeter and area of a square.

Thanks

Upvotes: 0

Views: 277

Answers (2)

Jason
Jason

Reputation: 11822

First, you should try to follow the naming standards for java classes by starting with a capital letter.

Square mySquare = new Square(10.0);
double theArea = mySquare.area();
double thePerimeter = mySquare.perimeter();

These calls to area() and perimeter() are using the implementations in Rectangle simply because they have not been overridden in Square.

Upvotes: 1

EDToaster
EDToaster

Reputation: 3180

First of all, all class names, by convention, need to be capitalized.

Also, you don't need to write any additional code: just initialize the square and call the methods on that.

Square s = new Square(50d);
double area = s.area();
double perimeter = s.perimeter();

or just override the area and perimeter methods and return super methods in the square class:

double area(){
    return super.area();
}
double perimeter(){
    return super.perimeter();
}

the latter is useful if you need to do extra calculations specifically for the square class, but in this example, you don't need it.

Upvotes: 4

Related Questions