Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Constructors, exercise 02, slide no 50
- */
- /*
- * Rectangle class
- */
- public class Rectangle {
- // class final variables
- private static final int DEFAULT_WIDTH = 10;
- private static final int DEFAULT_HEIGHT = 10;
- // Rectangle object properties
- private int width = Rectangle.DEFAULT_WIDTH;
- private int height = Rectangle.DEFAULT_HEIGHT;
- // constructors
- public Rectangle() {
- this(DEFAULT_WIDTH, DEFAULT_HEIGHT);
- }
- public Rectangle(int width, int height) {
- this.setWidth(width);
- this.setHeight(height);
- }
- public Rectangle(Rectangle sourceRect) {
- this.width = sourceRect.width;
- this.height = sourceRect.height;
- }
- // getter and setter for width property
- public int getWidth() {
- return this.width;
- }
- public boolean setWidth(int width) {
- if (width < 0) {
- return false;
- }
- this.width = width;
- return true;
- }
- // getter and setter for height property
- public int getHeight() {
- return this.height;
- }
- public boolean setHeight(int height) {
- if (height < 0) {
- return false;
- }
- this.height = height;
- return true;
- }
- // get rectangle area
- public int getArea() {
- return this.width * this.height;
- }
- // get rectangle perimeter
- public int getPerimeter() {
- return 2 * (this.width + this.height);
- }
- // print a rectangle
- public void print() {
- System.out.println(this.toShape('*'));
- }
- public void print(char fillChar) {
- System.out.println(this.toShape(fillChar));
- }
- // get rectangle shape
- private String toShape(char fillChar) {
- String aRow = oneRow(fillChar) + "\n";
- String result = "";
- for (int i = 0; i < this.height; i += 1) {
- result += aRow;
- }
- return result;
- }
- private String oneRow(char fillChar) {
- String row = "";
- for (int i = 0; i < this.width; i += 1)
- row += fillChar;
- return row;
- }
- @Override
- public String toString() {
- return "Rectangle [width=" + width + ", height=" + height + "]";
- }
- }
- /*
- * RectangleTester class, including main
- */
- public class RectangleTester {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Rectangle r1 = new Rectangle(3, 5);
- Rectangle r2 = new Rectangle();
- System.out.println("r1\n" + r1.toString());
- r1.print();
- System.out.println("r2\n" + r2.toString());
- r2.print('$');
- r2.setWidth(7);
- r2.setHeight(r1.getHeight() + 1);
- System.out.println("r2\n" + r2.toString());
- r2.print('#');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement