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

Write a complete class which represents a Rectangle object. You should have an a

ID: 3847214 • Letter: W

Question

Write a complete class which represents a Rectangle object. You should have an argumented constructor which sets both the length and widths of the rectangle (double values). As well, the rectangle class should have accessors and mutators for all variables needed. The mutator functions and constructor should ensure that the value being set are valid (cannot be 0 or negative). Your class should also have a function getArea which calculates the area of the rectangle (length multiplied by width). Also write a tester class which tests ALL functionality of the class (you do not need to use user input).

Explanation / Answer

package sample1;

public class Rectangle{
  
   private double width;
   private double height;
   public double getWidth() {
       return width;
   }
   public void setWidth(double width) throws Exception {
   if(width>0.0){
       this.width = width;
   }
       else{
           throw new Exception("Invalid input");
       }
   }
   public double getHeight() {
       return height;
   }
   public void setHeight(double height) throws Exception {
   if(height>0.0){
       this.height = height;
   }
       else{
           throw new Exception("Invalid input");
       }
   }
   public Rectangle(double width, double height) throws Exception {
       super();
       if(width>0.0&&height>0.0){
       this.width = width;
       this.height = height;
       }
       else{
           throw new Exception("Invalid input");
       }
   }
   public Rectangle(){
      
   }
public double getArea(){
   return width*height;
}

}

// Test class
package sample1;

public class test{
public static void main(String [] args) throws Exception
{
Rectangle r=new Rectangle(10.0,20.0);
System.out.println("height :"+r.getHeight()+" width : "+r.getWidth()+" Area :"+r.getArea());
Rectangle r1=new Rectangle();

r1.setHeight(-2.0);
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote