定义一个抽象类(Shape),包括求周长getPerimeter和求面积getArea抽像方法,然后在子类中求长方形(Rectangje)和圆(Circle)的周长和面积。(请以txt文档形式提交代码或者) 1)完成Shape类,Circle类,Rectangle类的设计。 2)在测试类中定义一个Shape类型的数组存入几个Circle类对象和Rectange类对象,并利用一个环打印出所有图形的周长和面积。
时间: 2024-02-23 15:58:07 浏览: 69
以下是Java代码实现:
Shape.java
```java
public abstract class Shape {
public abstract double getPerimeter();
public abstract double getArea();
}
```
Circle.java
```java
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
```
Rectangle.java
```java
public class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double getPerimeter() {
return 2 * (length + width);
}
@Override
public double getArea() {
return length * width;
}
}
```
Test.java
```java
public class Test {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(5);
shapes[1] = new Rectangle(4, 6);
shapes[2] = new Circle(3);
for (Shape shape : shapes) {
System.out.println("Perimeter: " + shape.getPerimeter());
System.out.println("Area: " + shape.getArea());
System.out.println();
}
}
}
```
运行Test.java的输出结果为:
```
Perimeter: 31.41592653589793
Area: 78.53981633974483
Perimeter: 20.0
Area: 24.0
Perimeter: 18.84955592153876
Area: 28.274333882308138
```
阅读全文