package cse1030; import java.awt.Color; import princeton.introcs.StdDraw; /** * A square shape. A square has four equal sides with length greater than zero. * * @author CSE1030Z * */ public class Square extends Shape { private double length; /** * Create a square with position (0, 0), color blue, and side length 1. */ public Square() { super(); this.length = 1.0; } /** * Create a square with position (x, y), and the given side length and color. * * @param x the x coordinate of the position of the square * @param y the y coordinate of the position of the square * @param length the side length of the square * @param color the color of the square * @throws IllegalArgumentException if the length is zero or negative */ public Square(double x, double y, double length, Color color) { super(x, y, color); this.setLength(length); } /** * Create a square with the given position, side length, and color. * * @param position the position of the square * @param length the side length of the square * @param color the color of the square * @throws IllegalArgumentException if the length is zero or negative */ public Square(Point2D position, double length, Color color) { super(position, color); this.setLength(length); } /** * Get the side length of the square. * * @return the side length of the square */ public double getLength() { return this.length; } /** * Set the side length of the square. The length must be greater than zero. * * @param newLength the new side length of the square * @throws IllegalArgumentException if the length is zero or negative */ public void setLength(double newLength) { if (newLength <= 0.) { throw new IllegalArgumentException("length is zero or negative"); } this.length = newLength; } /** * Returns a string representation of the square. * *

* The string returned has the form: * *

* position: (x, y), color: (r, g, b), length: L where x * and y are the coordinates of the position, * r, g, and b are the * red, green, and blue components of the color in the range 0-255, * and L is the side length. * * @return a string representation of the square */ @Override public String toString() { return super.toString() + ", length: " + this.getLength(); } /** * Draws a filled square to StdDraw using the * position, side length, and color of this square. */ @Override public void draw() { StdDraw.setPenColor(this.getColor()); StdDraw.filledSquare(this.getPosition().getX(), this.getPosition().getY(), 0.5 * this.getLength()); } }