6. [after §7.10-easy] Rectangles : Write a class called Rectangle that creates a
ID: 3874699 • Letter: 6
Question
6. [after §7.10-easy] Rectangles : Write a class called Rectangle that creates and processes rectangular objects. Include a class variable that holds the total number of rectangles and instance variables for height and width. a constructor that creates a new rectangle with a given height and width. Provide methods that return the total number of rectangles, increase the height of a calling rectangle, increase the calling rectangle, and print the area of a calling rectangle. Include this main method rovide width of a public static void main(String args) Rectangle r1 = new Rectangle(); r1.printArea () Rectangle r2 new Rectangle (2, 4) r2.printArea) r2.addHeight (3) addWidth (3) r2.printArea) System.out.println( Total number of rectanglesRectangle.getNumofRectangles)) ) I/ end main With this main method your program should generate the following output: Sample session Rectangle's area = 0 Rectangle's area = 8 Rectangle's area 35 Total number of rectangles = 2Explanation / Answer
Rectangle.java
public class Rectangle {
//Declaring instance variables
private int height;
private int width;
//Declaring static variable
private static int count = 0;
//Zero argumented constructor
public Rectangle() {
count++;
}
//Parameterized constructor
public Rectangle(int height, int width) {
super();
this.height = height;
this.width = width;
count++;
}
// getters and setters
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public void addHeight(int h) {
height += h;
}
public void addWidth(int w) {
width += w;
}
//This method will calculate and display the area of the Rectangle
public void printArea() {
System.out.println("Rectangle's area = " + (width * height));
}
//This method will return the no of Rectangles Created
public static int getNumOfRectangles() {
return count;
}
}
_____________________
DemoClass.java
public class DemoClass {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.printArea();
Rectangle r2 = new Rectangle(2, 4);
r2.printArea();
r2.addHeight(3);
r2.addWidth(3);
r2.printArea();
System.out.println("Total number of rectangles = " + Rectangle.getNumOfRectangles());
}
}
_____________________
Output:
Rectangle's area = 0
Rectangle's area = 8
Rectangle's area = 35
Total number of rectangles = 2
_______________Could you plz rate me well.Thank You
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.