In: Computer Science
using java Create a class Rectangle with attributes length and width both are of type double. In your class you should provide the following:
class Rectangle{
private double length;
private double width;
//Constructor
public Rectangle() {
this.length = this.width = 1;
}
public double getLength() {
return length;
}
public void setLength(double length) {
if(length > 0.0 && length < 50.0)
this.length = length;
else
System.out.println("Invalid length");
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
if(width > 0.0 && width < 50.0)
this.width = width;
else
System.out.println("Invalid width");
}
public double getArea(){
return length * width;
}
public double getPerimeter(){
return 2 * (length + width);
}
public double getDiagonal(){
return Math.sqrt(Math.pow(length, 2) + Math.pow(width, 2));
}
public void print(){
System.out.println("Length: " + length);
System.out.println("Width: " + width);
System.out.println("Area: " + getArea());
System.out.println("Perimeter: " + getPerimeter());
System.out.println("Diagonal: " + getDiagonal());
}
//Main method to test Rectangle class
public static void main(String[] args){
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
System.out.println("Testing first object");
r1.setLength(40);
r1.setWidth(15);
r1.print();
System.out.println("\nTesting second object");
r2.setLength(60);
r2.setLength(20);
r2.setWidth(5);
r2.print();
}
}
SAMPLE OUTPUT:
