Design a class named Rectangle to represent a rectangle. The class contains two
ID: 3627167 • Letter: D
Question
Design a class named Rectangle to represent a rectangle. The class containstwo double data fields named width and height that specify the width and neight of the rectangle
A no-arg constructor that creates a rectangle with the specified width and height
A method named getArea() that returns the area of this rectangel
A method named getPerimeter() that returns the perimeter
Draw the UML diagram for the class. Implement the class. Write a test program that creates two rectangel objects one with width 4 and height 40 and the other with width 3.5 and height 35.9. Display the width, height, area, and perimeter of each rectangle in this order.
Explanation / Answer
public class Rectangle {
private double height;
private double width;
Rectangle(){
this.height=1;
this.width=1;
}
Rectangle(double width, double height) {
this.width=width;
this.height=height;
}
double getArea() {
return this.width*this.height;
}
double getPerimeter() {
return 2 *(this.width+this.height);
}
public String toString() {
// Prints output to two decimals.
java.text.DecimalFormat decimalFormat = new java.text.DecimalFormat("#.##");
String output= "Width : "+this.width+" "+
"Height : "+this.height+" "+
"Area : "+decimalFormat.format(getArea())+" "+
"Perimeter : "+decimalFormat.format(getPerimeter());
return output;
}
public static void main(String[] args) {
Rectangle objRectangle1 = new Rectangle(4,40);
Rectangle objRectangle2 = new Rectangle(3.5,35.9);
System.out.println(objRectangle1.toString());
System.out.println(objRectangle2.toString());
}
}
public class Rectangle {
private double height;
private double width;
Rectangle(){
this.height=1;
this.width=1;
}
Rectangle(double width, double height) {
this.width=width;
this.height=height;
}
double getArea() {
return this.width*this.height;
}
double getPerimeter() {
return 2 *(this.width+this.height);
}
public String toString() {
// Prints output to two decimals.
java.text.DecimalFormat decimalFormat = new java.text.DecimalFormat("#.##");
String output= "Width : "+this.width+" "+
"Height : "+this.height+" "+
"Area : "+decimalFormat.format(getArea())+" "+
"Perimeter : "+decimalFormat.format(getPerimeter());
return output;
}
public static void main(String[] args) {
Rectangle objRectangle1 = new Rectangle(4,40);
Rectangle objRectangle2 = new Rectangle(3.5,35.9);
System.out.println(objRectangle1.toString());
System.out.println(objRectangle2.toString());
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.