Question:
Consider the following class definition in Java:
public class Rectangle {
private int length;
private int width;
public Rectangle(int l, int w) {
length = l;
width = w;
}
public int getLength() {
return length;
}
public void setLength(int l) {
length = l;
}
public int getWidth() {
return width;
}
public void setWidth(int w) {
width = w;
}
}
a) Write a constructor method for the Rectangle class that takes no parameters and initializes the length and width both to 0.
b) Write a constructor method for the Rectangle class that takes a single parameter representing the length, and initializes the width to a value of 5.
c) Write a constructor method for the Rectangle class that takes two parameters representing the length and width, and ensures that both values are positive. If the provided values are negative or zero, set the length and width to 1.
Answer:
a) The constructor method for the Rectangle class that takes no parameters and initializes the length and width both to 0 can be defined as:
public Rectangle() {
length = 0;
width = 0;
}
b) The constructor method for the Rectangle class that takes a single parameter representing the length and initializes the width to a value of 5 can be defined as:
public Rectangle(int l) {
length = l;
width = 5;
}
c) The constructor method for the Rectangle class that takes two parameters representing the length and width, and ensures that both values are positive can be defined as:
public Rectangle(int l, int w) {
if (l > 0) {
length = l;
} else {
length = 1;
}
if (w > 0) {
width = w;
} else {
width = 1;
}
}
Explanation:
a) In the constructor method that takes no parameters, we simply initialize both length and width to 0.
b) In the constructor method that takes a single parameter representing the length, we assign the provided length value to length and set the width to a fixed value of 5.
c) In the constructor method that takes two parameters representing the length and width, we check whether each value is positive. If a value is positive, we assign it to the corresponding instance variable. Otherwise, we set the value to 1.
By implementing these constructors, we ensure that the Rectangle class can be instantiated with different combinations of parameter values, providing flexibility for different scenarios.