编写一个 Shape 接口,接口中有三个抽象方法 area ()、 perimeter ()、 get - ClassName (),分别用于计算图形的面积、周长以及获取类的名称;设计类 Circle (圆形)、 Square (正方形)、 Rectangle (矩形),实现接口 Shape 中的所有方法。创建一个包含 main 方法的类测试相关的类和接口。
时间: 2023-05-13 17:07:06 浏览: 149
好的,以下是我给出的代码:
```
public interface Shape {
double area();
double perimeter();
String getClassName();
}
public class Circle implements Shape {
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;
}
@Override
public String getClassName() {
return "Circle";
}
}
public class Square implements Shape {
private double side;
public Square(double side) {
this.side = side;
}
@Override
public double area() {
return side * side;
}
@Override
public double perimeter() {
return 4 * side;
}
@Override
public String getClassName() {
return "Square";
}
}
public class Rectangle implements Shape {
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);
}
@Override
public String getClassName() {
return "Rectangle";
}
}
public class ShapeTest {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape square = new Square(4);
Shape rectangle = new Rectangle(3, 5);
System.out.println(circle.getClassName() + " area: " + circle.area());
System.out.println(circle.getClassName() + " perimeter: " + circle.perimeter());
System.out.println(square.getClassName() + " area: " + square.area());
System.out.println(square.getClassName() + " perimeter: " + square.perimeter());
System.out.println(rectangle.getClassName() + " area: " + rectangle.area());
System.out.println(rectangle.getClassName() + " perimeter: " + rectangle.perimeter());
}
}
```
希望这个代码能够满足你的需求!
阅读全文