87 lines
2.2 KiB
Java
87 lines
2.2 KiB
Java
/*
|
|
* Author: CHEN Yongyuan (Walter) 1930006025 from OOP(1007)
|
|
* Date: 2022-04-14
|
|
* Description: Rectangle class inherited from Shape class
|
|
*/
|
|
|
|
public class Rectangle extends Shape {
|
|
private double width;
|
|
private double length;
|
|
|
|
/**
|
|
* Constructor
|
|
*
|
|
* @param x x coordinate of the center of the rectangle
|
|
* @param y y coordinate of the center of the rectangle
|
|
* @param width width of the rectangle
|
|
* @param length length of the rectangle
|
|
*/
|
|
public Rectangle(double x, double y, double width, double length) {
|
|
super(x, y);
|
|
this.width = width;
|
|
this.length = length;
|
|
}
|
|
|
|
/**
|
|
* Calculates the area of the rectangle.
|
|
*
|
|
* @return the area of the rectangle
|
|
*/
|
|
@Override
|
|
public double area() {
|
|
return width * length;
|
|
}
|
|
|
|
/**
|
|
* Resizing a rectangle changes its width and length to both be newSize.
|
|
*
|
|
* @param newSize the new size of the rectangle
|
|
*/
|
|
@Override
|
|
public void resize(double newSize) {
|
|
width = newSize;
|
|
length = newSize;
|
|
}
|
|
|
|
/**
|
|
* Overloading resizeing a nectangle changes its width and length to both be
|
|
* newWidth and newLength.
|
|
*
|
|
* @param newWidth the new width of the rectangle
|
|
* @param newLength the new length of the rectangle
|
|
*/
|
|
public void resize(double newWidth, double newLength) {
|
|
width = newWidth;
|
|
length = newLength;
|
|
}
|
|
|
|
/**
|
|
* Test.
|
|
*/
|
|
public static void testRectangle() {
|
|
Rectangle r = new Rectangle(1.2, 3.4, 4.0, 5.0);
|
|
// getX, getY, and move are inherited from Shape.
|
|
// area and resize come from Rectangle itself.
|
|
System.out.println(r.getX() == 1.2);
|
|
System.out.println(r.getY() == 3.4);
|
|
System.out.println(r.area() == 20.0);
|
|
// Move the rectangle. The area does not change.
|
|
r.move(7.8, 9.0);
|
|
System.out.println(r.getX() == 9.0);
|
|
System.out.println(r.getY() == 12.4);
|
|
System.out.println(r.area() == 20.0);
|
|
// Resize the rectangle. The area changes but not the position.
|
|
r.resize(12.0);
|
|
System.out.println(r.getX() == 9.0);
|
|
System.out.println(r.getY() == 12.4);
|
|
System.out.println(r.area() == 144.0);
|
|
// Resize the rectangle again with different width and length.
|
|
// The area changes but not the position.
|
|
r.resize(10.0, 15.0);
|
|
System.out.println(r.getX() == 9.0);
|
|
System.out.println(r.getY() == 12.4);
|
|
System.out.println(r.area() == 150.0);
|
|
|
|
}
|
|
}
|