用JAVA设计一个抽象类Shape(图形)包含求面积和周长的area0方法和perimeter0方法以及设置颜色的方法SetColor(,并利用Java多态技术设计其子类Circle(圆形)类和Triangle(三角形)类,并分别实现相应的求面积和求周长的方法。
时间: 2024-11-25 16:09:50 浏览: 9
首先,我们定义一个抽象类`Shape`,它包含了两个抽象方法`area0()`和`perimeter0()`,以及一个具体的方法`setColor()`来设置颜色:
```java
public abstract class Shape {
protected String color;
public Shape(String color) {
this.color = color;
}
// 抽象方法,用于计算形状的面积
public abstract double area0();
// 抽象方法,用于计算形状的周长
public abstract double perimeter0();
// 设置颜色的方法
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Shape [color=" + color + "]";
}
}
```
接下来,我们将设计两个子类`Circle`和`Triangle`,它们都是`Shape`的实例,并实现了各自的`area0()`和`perimeter0()`方法:
```java
public class Circle extends Shape {
private double radius;
public Circle(double radius, String color) {
super(color);
this.radius = radius;
}
@Override
public double area0() {
return Math.PI * radius * radius;
}
@Override
public double perimeter0() {
return 2 * Math.PI * radius;
}
@Override
public String toString() {
return "Circle [radius=" + radius + ", color=" + color + "]";
}
}
public class Triangle extends Shape {
private double a, b, c; // 假设a、b、c分别为三边长度
public Triangle(double a, double b, double c, String color) {
super(color);
this.a = a;
this.b = b;
this.c = c;
}
// 使用海伦公式计算三角形面积
private double triangleArea(double a, double b, double c) {
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
@Override
public double area0() {
return triangleArea(a, b, c);
}
@Override
public double perimeter0() {
return a + b + c;
}
@Override
public String toString() {
return "Triangle [a=" + a + ", b=" + b + ", c=" + c + ", color=" + color + "]";
}
}
```
现在,你可以创建`Shape`类型的对象,并根据需要创建`Circle`或`Triangle`的对象,它们会自动调用自己的相应方法来计算面积和周长。例如:
```java
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(5.0, "blue");
System.out.println("Circle area: " + circle.area0());
System.out.println("Circle perimeter: " + circle.perimeter0());
Shape triangle = new Triangle(3.0, 4.0, 5.0, "red");
System.out.println("Triangle area: " + triangle.area0());
System.out.println("Triangle perimeter: " + triangle.perimeter0());
}
}
```
阅读全文