设计抽象类GeometricObject及其子类Triangle和Circle
时间: 2024-03-15 16:46:04 浏览: 211
以下是GeometricObject抽象类及其子类Triangle和Circle的示例代码:
```java
// GeometricObject.java
public abstract class GeometricObject {
private String color;
private boolean filled;
public GeometricObject() {
color = "white";
filled = false;
}
public GeometricObject(String color, boolean filled) {
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 abstract double getArea();
public abstract double getPerimeter();
}
// Triangle.java
public class Triangle extends GeometricObject {
private double side1;
private double side2;
private double side3;
public Triangle(double side1, double side2, double side3) {
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 = getPerimeter() / 2;
return Math.sqrt(p * (p - side1) * (p - side2) * (p - side3));
}
@Override
public double getPerimeter() {
return side1 + side2 + side3;
}
}
// Circle.java
public class Circle extends GeometricObject {
private double radius;
public Circle(double radius) {
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 * Math.PI * radius;
}
}
```
GeometricObject抽象类中定义了几何对象的共同属性和方法,其中getArea和getPerimeter方法是抽象方法,需要在其子类中实现。Triangle和Circle类分别继承自GeometricObject抽象类,并实现了getArea和getPerimeter方法。
阅读全文