1.定义一个接口Shap2D,使用该接口实现二维几何图形类Circle(圆形)和Rectangle(矩形)面积的计算,编写实现接口的类以及测试类。(java实现)
时间: 2024-10-25 14:09:40 浏览: 25
首先,我们需要定义一个名为`Shape2D`的接口,它包含一个用于计算面积的方法`getArea()`:
```java
public interface Shape2D {
double getArea();
}
```
接着,我们创建两个实现了这个接口的具体类:`Circle`和`Rectangle`。
对于`Circle`类:
```java
import java.util.Scanner;
public class Circle implements Shape2D {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
// 主函数可以省略,这里仅为了演示
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the circle's radius: ");
double inputRadius = scanner.nextDouble();
Circle circle = new Circle(inputRadius);
System.out.println("The area of the circle is: " + circle.getArea());
}
}
```
对于`Rectangle`类:
```java
public class Rectangle implements Shape2D {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
// 同样,主函数可以省略
}
```
最后,我们可以创建一个测试类`TestShape2D`来验证这两个类是否正确实现了接口:
```java
public class TestShape2D {
public static void main(String[] args) {
Shape2D circle = new Circle(5.0);
Shape2D rectangle = new Rectangle(4.0, 6.0);
System.out.println("Circle area: " + circle.getArea());
System.out.println("Rectangle area: " + rectangle.getArea());
}
}
```
在这个例子中,`Circle`和`Rectangle`都实现了`Shape2D`接口,并提供了各自的面积计算方法。当你运行`TestShape2D`时,会分别打印出圆形和矩形的面积。
阅读全文