设计一个Shape接口和它的两个实现类Square和Circle Shape接口中有一个抽象方法area(),方法接受有一个 double类型的参数,返回一个 double类型的结果。 (2).Square和Circle中实现了Shape接口的area()抽象方法,分别求正方形和圆形的面积并返回。 在测试类中创建Square和Circle对象,计算边长为2的正方形的面积和半径为3的圆形面积
时间: 2024-03-17 08:44:52 浏览: 61
设计一个Shape接口和它的两个实现类Square和Circle,要求如下
好的,我理解了你的问题。下面是Shape接口及其两个实现类Square和Circle的代码:
```java
public interface Shape {
double area(double param);
}
public class Square implements Shape {
@Override
public double area(double param) {
return param * param;
}
}
public class Circle implements Shape {
@Override
public double area(double param) {
return Math.PI * param * param;
}
}
```
在测试类中,我们可以创建Square和Circle对象,分别计算边长为2的正方形的面积和半径为3的圆形面积,代码如下:
```java
public class Test {
public static void main(String[] args) {
Shape square = new Square();
Shape circle = new Circle();
double squareArea = square.area(2);
double circleArea = circle.area(3);
System.out.println("The area of a square with side length 2 is: " + squareArea);
System.out.println("The area of a circle with radius 3 is: " + circleArea);
}
}
```
运行结果为:
```
The area of a square with side length 2 is: 4.0
The area of a circle with radius 3 is: 28.274333882308138
```
阅读全文