1)(10分)完成Shape接口,Circle类,Rectangle类的设计。 定义一个接口(Shape),包括求周长getPerimeter和求面积getArea抽象力法,然后在实现美Circle类和Rectangle类中求长方形(Rectangle)和圆(Circle)的周长和面积。2)(10分)在测试类中定义一个Shape类型的数组存入几个Crle类对象和Rectangle类对象,井利用一个情坏打印出所有图形的周长和面积。循环输出的过程如下:半径是5.0的圆的周长是:31.40000000000002半径是5.0的圆的面积是:78.5 半径是8.0的圆的周长是:50.24 半径是8.0的圆的面积是:200.96 长为25.0,宽为8.0的长方形的周长是:400.0长为25.0,宽为8.0的长方形的面积是:200.0长为11.0,宽为5.0的长方形的周长是:110.0长为11.0,宽为5.0的长方形的面积是:55.0
时间: 2024-02-23 21:58:51 浏览: 101
好的,这是一个Java代码实现Shape接口、Circle类和Rectangle类,并在测试类中打印周长和面积的示例:
Shape.java
```java
public interface Shape {
double getPerimeter();
double getArea();
}
```
Circle.java
```java
public class Circle implements Shape {
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;
}
}
```
Rectangle.java
```java
public class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getPerimeter() {
return 2 * (length + width);
}
public double getArea() {
return length * width;
}
}
```
Test.java
```java
public class Test {
public static void main(String[] args) {
Shape[] shapes = {
new Circle(5.0),
new Circle(8.0),
new Rectangle(25.0, 8.0),
new Rectangle(11.0, 5.0)
};
for (Shape shape : shapes) {
if (shape instanceof Circle) {
Circle circle = (Circle) shape;
System.out.println("半径是" + circle.radius + "的圆的周长是:" + circle.getPerimeter());
System.out.println("半径是" + circle.radius + "的圆的面积是:" + circle.getArea());
} else if (shape instanceof Rectangle) {
Rectangle rectangle = (Rectangle) shape;
System.out.println("长为" + rectangle.length + ",宽为" + rectangle.width + "的长方形的周长是:" + rectangle.getPerimeter());
System.out.println("长为" + rectangle.length + ",宽为" + rectangle.width + "的长方形的面积是:" + rectangle.getArea());
}
}
}
}
```
输出结果:
```
半径是5.0的圆的周长是:31.41592653589793
半径是5.0的圆的面积是:78.53981633974483
半径是8.0的圆的周长是:50.26548245743669
半径是8.0的圆的面积是:201.06192982974676
长为25.0,宽为8.0的长方形的周长是:66.0
长为25.0,宽为8.0的长方形的面积是:200.0
长为11.0,宽为5.0的长方形的周长是:32.0
长为11.0,宽为5.0的长方形的面积是:55.0
```
阅读全文