Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Lab 4 Write the code for a class named Rectangle to represent a rectangle. The class contains: Two instance variables width and height. A constructor

Lab 4

Write the code for a class named Rectangle to represent a rectangle. The class contains:

  • Two instance variables width and height.
  • A constructor that constructs a rectangle with the specified width and height, with default values 1 and 2 for the width and height, respectively.
  • An __str__ method that returns a string representation of the form "Rectangle with width valueOfWidth and height valueOfHeight".
  • A method named getArea() that returns the area of this rectangle.
  • A method named getPerimeter() that returns the perimeter.
  • A method named isSquare() that returns True if the rectangle is a square and False otherwise.

Add a test program (i.e., main function) that does the following:

  • Creates three rectangle objects --the first with width 5 and height 3, the second with width 2.5 and height 2.5, and the third with default values for width and height. Notice that when you create the third object, you need to take advantage of the fact that the constructor method sets default values to some or all of its parameters when no values are passed to these parameters.
  • Print the three objects (this tests the __str__ method). Notice that if r1 is an object of type Rectange, then print(r1) automatically calls the __str__ method of the calss.
  • Display the area and perimeter of each object.
  • Call the method isSquare() on each objects.

Sample program output is as follows:

Rectangle with width 5 and height 3 Area is: 15 Perimeter is: 16 Is this rectangle actually a square? False Rectangle with width 2.5 and height 2.5 Area is: 6.25 Perimeter is: 10.0 Is this rectangle actually a square? True Rectangle with width 1 and height 2 Area is: 2 Perimeter is: 6 Is this rectangle actually a square? False 

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions