Consider the following Rectangle
class:
public class Rectangle {
private int length;
private int width;
public Rectangle(int length, int width) {
this.length = length;
this.width = width;
}
public int getLength() {
return length;
}
public int getWidth() {
return width;
}
public void setLength(int length) {
this.length = length;
}
public void setWidth(int width) {
this.width = width;
}
public int calculateArea() {
return length * width;
}
}
Modify the Rectangle
class to include an instance variable color
of type String
. Provide appropriate getter and setter methods for color
.
Suppose you have two Rectangle
objects rect1
and rect2
with lengths 5 and 7 respectively, and widths 3 and 4 respectively. Write a code snippet to:
rect1
to "blue".rect2
to "green".rect1
in a variable called area1
.rect2
in a variable called area2
.Suppose you have a Square
class that extends the Rectangle
class. The Square
class should have a single parameter constructor that takes an integer side length and calls the superclass constructor to set both the length and width equal to the side length. Implement the Square
class accordingly.
Write code to create a Square
object square1
with side length 6, and set the color of square1
to "yellow". Calculate and store the area of square1
in a variable called areaSquare1
.
Note: Assume that the necessary import statements are already included.
Rectangle
class:public class Rectangle {
private int length;
private int width;
private String color;
public Rectangle(int length, int width) {
this.length = length;
this.width = width;
}
public int getLength() {
return length;
}
public int getWidth() {
return width;
}
public void setLength(int length) {
this.length = length;
}
public void setWidth(int width) {
this.width = width;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int calculateArea() {
return length * width;
}
}
public class Main {
public static void main(String[] args) {
Rectangle rect1 = new Rectangle(5, 3);
Rectangle rect2 = new Rectangle(7, 4);
rect1.setColor("blue");
rect2.setColor("green");
int area1 = rect1.calculateArea();
int area2 = rect2.calculateArea();
}
}
Square
class:public class Square extends Rectangle {
public Square(int sideLength) {
super(sideLength, sideLength);
}
}
Square
object:public class Main {
public static void main(String[] args) {
Square square1 = new Square(6);
square1.setColor("yellow");
int areaSquare1 = square1.calculateArea();
}
}
In the solution, we modified the Rectangle
class to include the color
instance variable and the corresponding getter and setter methods. We also created a Square
class that extends the Rectangle
class and implemented a constructor to set both the length and width equal to the side length. Finally, we created objects and performed color setting and area calculation operations as required.