Question:
Consider the following class definition:
public class Rectangle {
private int width;
private int height;
public Rectangle(int w, int h) {
width = w;
height = h;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public int getArea() {
return width * height;
}
public void scale(int factor) {
width *= factor;
height *= factor;
}
}
You are given the Rectangle
class above, which represents a rectangle shape. Using this class, you are required to write a program that does the following:
Rectangle
object named rect
with width 5 and height 3.rect
.rect
by a factor of 2.rect
.Write the necessary code in the main
method to complete the above tasks.
Explanation:
To complete the given tasks, the following code can be used:
public class Main {
public static void main(String[] args) {
Rectangle rect = new Rectangle(5, 3);
// Printing the area of rect
System.out.println("Area of rectangle: " + rect.getArea());
// Scaling rect by a factor of 2
rect.scale(2);
// Printing the updated area of rect
System.out.println("Updated area of rectangle: " + rect.getArea());
}
}
In the main
method, we create a Rectangle
object named rect
with width 5 and height 3. We then print the area of rect
using the getArea()
method. Next, we scale rect
by a factor of 2 using the scale()
method. Finally, we print the updated area of rect
again using the getArea()
method.
The output of the above code will be:
Area of rectangle: 15
Updated area of rectangle: 60
The area of the rectangle initially is 15 (width: 5, height: 3), and after scaling it by a factor of 2, the new area becomes 60 (new width: 10, new height: 6).