编写一个名为Octagon的类,它继承自GeometricObject类并实现Comparable和Cloneable接口。假设八边形八条边的边长都相等。它的面积可以使用下面的公式计算: 面积 = ( 2 + 4 / √ 2 ) × 边长 × 边长 面积=(2+4/√2)×边长×边长面积=(2+4/√2)×边长×边长 画出包括Octagon、GeometricObject、Comparable和Cloneable的UML图。编写一个测试程序,创建一个边长值为5的Octagon对象,然后显示它的面积和周长。使用clone方法创建一个新对象,并使用compareTo方法比较这两个对象。
时间: 2024-01-22 08:17:40 浏览: 74
以下是Octagon、GeometricObject、Comparable和Cloneable的UML图:
```
--------------------------------
| GeometricObject |
--------------------------------
|+color: String |
|+filled: boolean |
|+dateCreated: Date |
|+GeometricObject() |
|+GeometricObject(color: String, filled: boolean) |
|+getColor(): String |
|+setColor(color: String): void|
|+isFilled(): boolean |
|+setFilled(filled: boolean): void |
|+getDateCreated(): Date |
|+toString(): String |
|+getArea(): double |
|+getPerimeter(): double |
|+compareTo(object: Object): int|
|+clone(): Object |
--------------------------------
^
|
|
|
--------------------------------
| Comparable |
--------------------------------
|+compareTo(object: Object): int|
--------------------------------
^
|
|
|
--------------------------------
| Cloneable |
--------------------------------
|+clone(): Object |
--------------------------------
^
|
|
|
--------------------------------
| Octagon |
--------------------------------
|-side: double |
|+Octagon() |
|+Octagon(side: double) |
|+getSide(): double |
|+setSide(side: double): void |
|+getArea(): double |
|+getPerimeter(): double |
|+compareTo(octagon: Octagon): int |
|+clone(): Object |
--------------------------------
```
以下是 Octagon 类的实现:
```
public class Octagon extends GeometricObject implements Comparable<Octagon>, Cloneable {
private double side;
public Octagon() {
this(1.0);
}
public Octagon(double side) {
this.side = side;
}
public double getSide() {
return side;
}
public void setSide(double side) {
this.side = side;
}
@Override
public double getArea() {
return (2 + 4 / Math.sqrt(2)) * side * side;
}
@Override
public double getPerimeter() {
return 8 * side;
}
@Override
public int compareTo(Octagon o) {
if (getArea() > o.getArea()) {
return 1;
} else if (getArea() < o.getArea()) {
return -1;
} else {
return 0;
}
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
```
以下是测试程序:
```
public class TestOctagon {
public static void main(String[] args) {
Octagon octagon = new Octagon(5);
System.out.println("Area: " + octagon.getArea());
System.out.println("Perimeter: " + octagon.getPerimeter());
try {
Octagon octagon2 = (Octagon) octagon.clone();
int result = octagon.compareTo(octagon2);
if (result == 1) {
System.out.println("The original octagon has a larger area than the cloned octagon.");
} else if (result == -1) {
System.out.println("The cloned octagon has a larger area than the original octagon.");
} else {
System.out.println("Both octagons have the same area.");
}
} catch (CloneNotSupportedException ex) {
ex.printStackTrace();
}
}
}
```
阅读全文