java设计抽象类GeometricObject及其子类Triangle和Circle。 GeometricObject类设计要求如下: ■ 一个名为color 的Color类型的私有数据域,表示对象的颜色。 ■ 一个名为filled 的Boolean类型的私有数据域,表示对象是否填充颜色。 ■ 一个名为dateCreated的Date类型的私有数据域,表示对象的创建日期。 ■ 一个无参构造方法
时间: 2024-03-05 09:53:49 浏览: 174
GeometricObject.java
以下是GeometricObject及其子类Triangle和Circle的Java代码实现:
```java
import java.util.Date;
public abstract class GeometricObject {
private String color;
private boolean filled;
private Date dateCreated;
public GeometricObject() {
this.color = "white";
this.filled = false;
this.dateCreated = new Date();
}
public GeometricObject(String color, boolean filled) {
this.color = color;
this.filled = filled;
this.dateCreated = new Date();
}
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 Date getDateCreated() {
return dateCreated;
}
public abstract double getArea();
public abstract double getPerimeter();
}
public class Triangle extends GeometricObject {
private double side1;
private double side2;
private double side3;
public Triangle() {
super();
this.side1 = 1.0;
this.side2 = 1.0;
this.side3 = 1.0;
}
public Triangle(double side1, double side2, double side3) {
super();
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public double getSide1() {
return side1;
}
public void setSide1(double side1) {
this.side1 = side1;
}
public double getSide2() {
return side2;
}
public void setSide2(double side2) {
this.side2 = side2;
}
public double getSide3() {
return side3;
}
public void setSide3(double side3) {
this.side3 = side3;
}
@Override
public double getArea() {
double p = (side1 + side2 + side3) / 2.0;
return Math.sqrt(p * (p - side1) * (p - side2) * (p - side3));
}
@Override
public double getPerimeter() {
return side1 + side2 + side3;
}
}
public class Circle extends GeometricObject {
private double radius;
public Circle() {
super();
this.radius = 1.0;
}
public Circle(double radius) {
super();
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public double getPerimeter() {
return 2.0 * Math.PI * radius;
}
}
```
GeometricObject类具有颜色、是否填充和创建日期等属性,并且定义了抽象方法getArea和getPerimeter计算面积和周长。Triangle和Circle都继承了GeometricObject,并实现了抽象方法getArea和getPerimeter。Triangle还具有三边长的属性,而Circle具有半径的属性。
阅读全文