创建一个描述三角形的类Triangle,类中有三边长,面积,周长等成员变量,有带参数的构造方法,以及计算面积、计算周长和输出信息等成员方法,再创建描述圆形的类Circle,其中有半径、面积、周长等属性,有带参数的构造方法,以及计算面积、计算周长和输出信息等成员方法,在主类中测试三角形类和圆形类的使用(创建对象,计算面积、周长,输出信息)使用Java语言
时间: 2023-05-11 13:07:28 浏览: 78
以下是 Triangle 和 Circle 类的代码:
```java
class Triangle {
private double a, b, c;
private double area, perimeter;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
calculateArea();
calculatePerimeter();
}
private void calculateArea() {
double p = (a + b + c) / 2;
area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
private void calculatePerimeter() {
perimeter = a + b + c;
}
public void printInfo() {
System.out.println("Triangle with sides " + a + ", " + b + ", " + c);
System.out.println("Area: " + area);
System.out.println("Perimeter: " + perimeter);
}
}
class Circle {
private double radius;
private double area, perimeter;
public Circle(double radius) {
this.radius = radius;
calculateArea();
calculatePerimeter();
}
private void calculateArea() {
area = Math.PI * radius * radius;
}
private void calculatePerimeter() {
perimeter = 2 * Math.PI * radius;
}
public void printInfo() {
System.out.println("Circle with radius " + radius);
System.out.println("Area: " + area);
System.out.println("Perimeter: " + perimeter);
}
}
```
以下是主类中测试 Triangle 和 Circle 类的代码:
```java
public class Main {
public static void main(String[] args) {
Triangle t = new Triangle(3, 4, 5);
t.printInfo();
Circle c = new Circle(2);
c.printInfo();
}
}
```
输出结果为:
```
Triangle with sides 3.0, 4.0, 5.0
Area: 6.0
Perimeter: 12.0
Circle with radius 2.0
Area: 12.566370614359172
Perimeter: 12.566370614359172
```
希望这个回答能够帮到你!
阅读全文