用java1、为Circle和Rectangle类定义一个抽象父类GeometricObject. GeometricObject类中的数据域、构造方法和普通方法可以参考书上432页程序清单13-1. 2、在GeometricObject抽象类中添加抽象方法,包括getArea(), getPerimeter(). 3、 必要情况下,改写原Circle和Rectangle类中的重写方法。 4、 修改GeometricObject类以实现Comparable接口,并且在GeometricObject类中定义一个静态的max方法,用于求两个GeometricObject对象的面积较大者。 5、编写测试程序,对于任意的Circle或者Rectangle的对象,用多态实现Circle和Rectangle类中的求面积、求周长的程序。 6、编写测试程序,使用max方法求任意两个几何形状(如两个圆、两个矩形、一个圆和一个矩形)之间的面积较大者。
时间: 2024-03-17 16:41:38 浏览: 70
好的,我会按照你的要求回答问题。
1. 以下是GeometricObject抽象类的代码:
```java
public abstract class GeometricObject {
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;
protected GeometricObject() {
dateCreated = new java.util.Date();
}
protected GeometricObject(String color, boolean filled) {
dateCreated = new java.util.Date();
this.color = color;
this.filled = filled;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
this.filled = filled;
}
public java.util.Date getDateCreated() {
return dateCreated;
}
public String toString() {
return "created on " + dateCreated + "\ncolor: " + color +
" and filled: " + filled;
}
public abstract double getArea();
public abstract double getPerimeter();
}
```
2. 在GeometricObject抽象类中添加了抽象方法getArea()和getPerimeter()。
3. Circle和Rectangle类中不需要改写原有的方法,因为它们都已经重写了GeometricObject中的方法。
4. 以下是修改后的GeometricObject类,实现了Comparable接口和max方法:
```java
public abstract class GeometricObject implements Comparable<GeometricObject> {
// 省略其他代码
public static GeometricObject max(GeometricObject obj1, GeometricObject obj2) {
if (obj1.compareTo(obj2) > 0) {
return obj1;
} else {
return obj2;
}
}
public int compareTo(GeometricObject obj) {
double area1 = this.getArea();
double area2 = obj.getArea();
if (area1 > area2) {
return 1;
} else if (area1 < area2) {
return -1;
} else {
return 0;
}
}
}
```
5. 以下是使用多态实现Circle和Rectangle类中的求面积、求周长的程序的测试代码:
```java
public class Test {
public static void main(String[] args) {
GeometricObject[] objects = new GeometricObject[2];
objects[0] = new Circle(5);
objects[1] = new Rectangle(2, 4);
for (int i = 0; i < objects.length; i++) {
System.out.println("Area of object " + (i + 1) + " is " + objects[i].getArea());
System.out.println("Perimeter of object " + (i + 1) + " is " + objects[i].getPerimeter());
}
}
}
```
6. 以下是使用max方法求任意两个几何形状之间的面积较大者的测试代码:
```java
public class Test {
public static void main(String[] args) {
GeometricObject obj1 = new Circle(5);
GeometricObject obj2 = new Rectangle(2, 4);
GeometricObject maxObj = GeometricObject.max(obj1, obj2);
System.out.println("The max object is:");
System.out.println(maxObj);
System.out.println("The area of max object is " + maxObj.getArea());
}
}
```
阅读全文