Java设计一个IShape接口和它的三个实现类,要求如下: Ishape接口中有两个方法,area方法用于返回面积,perimeter方法返回周长。 正方形类Square、长方形类Rectangle和圆类Circle实现了接口中的抽象方法,计算了正方形、长方形及圆形的面积、周长。 在测试类创建计算边长为2的正方形对象,创建长为5、宽为2.5的长方形对象,创建半径为3的圆形对象,分别计算他们的面积、周长
时间: 2024-02-19 17:57:56 浏览: 172
好的,以下是Java代码实现,包括IShape接口和三个实现类Square、Rectangle和Circle,以及测试类:
IShape.java
```java
public interface IShape {
double area();
double perimeter();
}
```
Square.java
```java
public class Square implements IShape {
private double side;
public Square(double side) {
this.side = side;
}
@Override
public double area() {
return side * side;
}
@Override
public double perimeter() {
return 4 * side;
}
}
```
Rectangle.java
```java
public 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 area() {
return length * width;
}
@Override
public double perimeter() {
return 2 * (length + width);
}
}
```
Circle.java
```java
public class Circle implements IShape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
@Override
public double perimeter() {
return 2 * Math.PI * radius;
}
}
```
TestIShape.java
```java
public class TestIShape {
public static void main(String[] args) {
Square square = new Square(2);
System.out.println("正方形的面积为:" + square.area());
System.out.println("正方形的周长为:" + square.perimeter());
Rectangle rectangle = new Rectangle(5, 2.5);
System.out.println("长方形的面积为:" + rectangle.area());
System.out.println("长方形的周长为:" + rectangle.perimeter());
Circle circle = new Circle(3);
System.out.println("圆形的面积为:" + circle.area());
System.out.println("圆形的周长为:" + circle.perimeter());
}
}
```
输出结果:
```
正方形的面积为:4.0
正方形的周长为:8.0
长方形的面积为:12.5
长方形的周长为:15.0
圆形的面积为:28.274333882308138
圆形的周长为:18.84955592153876
```
阅读全文