用java 1定义接口IShape,该接口有2个方法,方法一(求周长):double perimeter(),方法二(求面积):double area();2自行定义圆类(Circle),实现IShape接口;3自行定义矩形类(Rectagle),实现IShape接口;然后进行测试
时间: 2023-12-10 17:41:43 浏览: 60
好的,以下是实现的Java代码:
```java
interface IShape {
double perimeter(); // 求周长
double area(); // 求面积
}
class Circle implements IShape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double perimeter() {
return 2 * Math.PI * radius;
}
@Override
public double area() {
return Math.PI * Math.pow(radius, 2);
}
}
class Rectangle implements IShape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double perimeter() {
return 2 * (length + width);
}
@Override
public double area() {
return length * width;
}
}
public class Test {
public static void main(String[] args) {
Circle circle = new Circle(5);
Rectangle rectangle = new Rectangle(3, 4);
System.out.println("圆的周长:" + circle.perimeter());
System.out.println("圆的面积:" + circle.area());
System.out.println("矩形的周长:" + rectangle.perimeter());
System.out.println("矩形的面积:" + rectangle.area());
}
}
```
输出结果为:
```
圆的周长:31.41592653589793
圆的面积:78.53981633974483
矩形的周长:14.0
矩形的面积:12.0
```
阅读全文