Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a Rectangle class that models a Rectangle. It should have integer length

ID: 3855374 • Letter: C

Question

Create a Rectangle class that models a Rectangle. It should have integer length and width attributes. The Rectangle class should also be able to draw a rectangle on the standard output device, using a single character that is specified by the user, and should compute the area and perimeter of rectangles. Valid values for length and width are integers in the range 1-30.

Include appropriate get and set methods, and other methods that may be required to adequately model rectangles.

Create a program called TestRectangle that tests the methods in the Rectangle class

Explanation / Answer

Rectangle.java file

public class Rectangle{
  
   private int length;
   private int breadth;
  
   /* constructor to set length and breadth of rectangle */
   public Rectangle(int l,int b){
       length = l;
       breadth = b;
   }
  
   /* setter method of length */
   public void setLength(int l){
       length = l;
   }
  
   /* setter method of breadth */
   public void setBreadth(int b){
       breadth = b;
   }
  
   /* getter method of length */
   public int getLength(){
       return length;
   }
  
   /* getter method of breadth */
   public int getBreadth(){
       return breadth;
   }
  
   /* calculates and returns area */
   public int getArea(){
       return length*breadth;
   }
  
   /* calculates and returns perimeter */
   public int getPerimeter(){
       return 2*(length+breadth);
   }
  
   /* prints rectangle to console */
   public void showRectangle(char c){
       for(int i=0;i<length;i++){
           for(int j=0;j<breadth;j++){
               System.out.print(c);
           }
           System.out.println();
       }
      
   }
}

TestRectangle.java file

public class TestRectangle{
   public static void main(String args[]){
       Rectangle rt = new Rectangle(4,8);
       System.out.println();
       System.out.println("Length : "+rt.getLength());
       System.out.println("Breadth : "+rt.getBreadth());
       System.out.println();
       rt.showRectangle('*');
       System.out.println();
       System.out.println("Area : " +rt.getArea());
       System.out.println("Peri : "+rt.getPerimeter());
   }
}

/*

sample output


Length : 4
Breadth : 8

********
********
********
********

Area : 32
Peri : 24

*/