Write a Rectangle class with three constructors – no arguments (1×1), one argument (a square) and two arguments – chained with this(...), and print the area of each kind.
class Rectangle {
private final double length, width;
Rectangle() { this(1); }
Rectangle(double side) { this(side, side); }
Rectangle(double length, double width) {
if (length <= 0 || width <= 0) throw new IllegalArgumentException("sides must be positive");
this.length = length;
this.width = width;
}
double area() { return length * width; }
boolean isSquare() { return length == width; }
@Override public String toString() { return length + " x " + width; }
}
public class Main {
public static void main(String[] args) {
Rectangle[] rs = {new Rectangle(), new Rectangle(4), new Rectangle(6, 2.5)};
for (Rectangle r : rs) System.out.printf("%-10s area %5.2f square=%b%n", r, r.area(), r.isSquare());
}
}
1.0 x 1.0 area 1.00 square=true 4.0 x 4.0 area 16.00 square=true 6.0 x 2.5 area 15.00 square=false
All validation lives in the two-argument constructor; the others delegate to it.