声明一个Shape接口,其中有计算面积(方法名area)、周长(方法名perimeter)的方法,有以下几个实现:Circle(圆),Rectangle(矩形),Triangle(三角形),都有计算面积、周长的方法。 编写TestShape类,用于测试
时间: 2024-10-16 19:12:30 浏览: 64
声明Shape接口可以这样设计:
```java
public interface Shape {
double area(); // 计算面积
double perimeter(); // 计算周长
}
```
接着,我们为每个形状实现这个接口:
```java
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;
}
}
public class Rectangle implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double area() {
return width * height;
}
@Override
public double perimeter() {
return 2 * (width + height);
}
}
public class Triangle implements Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double area() {
return 0.5 * base * height;
}
@Override
public double perimeter() {
// 假设这是一个等腰三角形,仅计算底边+两腰
// 实际情况可能需要提供具体的三边长度
double side = base / 2;
return base + 2 * side;
}
}
```
最后,我们创建TestShape类来进行测试:
```java
public class TestShape {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);
Shape triangle = new Triangle(3, 4);
System.out.println("Circle area: " + circle.area());
System.out.println("Circle perimeter: " + circle.perimeter());
System.out.println("Rectangle area: " + rectangle.area());
System.out.println("Rectangle perimeter: " + rectangle.perimeter());
System.out.println("Triangle area: " + triangle.area());
System.out.println("Triangle perimeter: " + triangle.perimeter());
}
}
```
在这个例子中,`TestShape`类通过Shape接口对各种形状的对象进行了操作,体现了多态性,即不关心具体的形状,只关注共同的行为。
阅读全文