测试类TestGeometricObject1设计要求如下: ■ 一个能随机生成Circle类和Triangle类对象的静态方法 GeometricObject[] RandomCreateGeometricObject() ■ 以随机生成的数组为参数,输出数组中每个对象的基本信息、周长和面积。 ■ 类中其它方法的测试 java
时间: 2024-02-27 19:52:54 浏览: 71
Java提升学习(二):构造方法,类的继承,封装
好的,我会为你解答这个问题。
首先,我们需要创建一个GeometricObject类,作为Circle类和Triangle类的父类。GeometricObject类中需要包含计算周长和面积的方法,以及输出基本信息的方法。具体代码如下:
```java
public abstract class GeometricObject {
public abstract double getPerimeter();
public abstract double getArea();
public abstract void printInfo();
}
```
接着,我们创建Circle类和Triangle类,分别继承GeometricObject类,并实现其抽象方法。具体代码如下:
```java
public class Circle extends GeometricObject {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getPerimeter() {
return 2 * Math.PI * radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public void printInfo() {
System.out.println("Circle: radius = " + radius + ", perimeter = " + getPerimeter() + ", area = " + getArea());
}
}
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 getPerimeter() {
return side1 + side2 + side3;
}
public double getArea() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
public void printInfo() {
System.out.println("Triangle: side1 = " + side1 + ", side2 = " + side2 + ", side3 = " + side3 + ", perimeter = " + getPerimeter() + ", area = " + getArea());
}
}
```
接下来,我们创建TestGeometricObject1类,实现随机生成GeometricObject数组、输出数组中每个对象的基本信息、周长和面积的方法。具体代码如下:
```java
import java.util.Random;
public class TestGeometricObject1 {
public static GeometricObject[] RandomCreateGeometricObject() {
GeometricObject[] objs = new GeometricObject[10];
Random random = new Random();
for (int i = 0; i < 10; i++) {
if (random.nextBoolean()) {
objs[i] = new Circle(random.nextDouble() * 10);
} else {
objs[i] = new Triangle(random.nextDouble() * 10, random.nextDouble() * 10, random.nextDouble() * 10);
}
}
return objs;
}
public static void printGeometricObjects(GeometricObject[] objs) {
for (int i = 0; i < objs.length; i++) {
objs[i].printInfo();
}
}
public static void main(String[] args) {
GeometricObject[] objs = RandomCreateGeometricObject();
printGeometricObjects(objs);
}
}
```
最后,我们运行TestGeometricObject1类,即可得到随机生成的GeometricObject数组,并输出每个对象的基本信息、周长和面积。
我希望这个解答能够帮到你!
阅读全文