Java定义一个图形接口,包含周长和面积方法。声明三角形、矩形和圆形类,实现上述接口。用Java代码实现
时间: 2024-12-25 19:37:37 浏览: 23
在Java中,我们可以首先定义一个`Shape`接口,它包含了计算周长`perimeter()`和面积`area()`的方法。然后,我们创建三个具体的形状类`Triangle`, `Rectangle`, 和 `Circle`,它们分别继承自`Shape`接口,并提供各自的实现。
```java
// 定义Shape接口
public interface Shape {
double perimeter();
double area();
}
// 实现三角形类
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 perimeter() {
return base + (base * 0.5); // 假设这是一个等腰三角形,只给出一个边长
}
@Override
public double area() {
return 0.5 * base * height;
}
}
// 实现矩形类
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 perimeter() {
return 2 * (length + width);
}
@Override
public double area() {
return length * width;
}
}
// 实现圆形类
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double perimeter() {
return 2 * Math.PI * radius; // 使用Math.PI计算圆的周长
}
@Override
public double area() {
return Math.PI * Math.pow(radius, 2); // 计算圆的面积
}
}
```
现在,你可以创建并使用这三个类的对象,因为它们都实现了`Shape`接口:
```java
public class Main {
public static void main(String[] args) {
Triangle triangle = new Triangle(4, 6);
Rectangle rectangle = new Rectangle(5, 7);
Circle circle = new Circle(3);
System.out.println("Triangle perimeter: " + triangle.perimeter());
System.out.println("Triangle area: " + triangle.area());
System.out.println("Rectangle perimeter: " + rectangle.perimeter());
System.out.println("Rectangle area: " + rectangle.area());
System.out.println("Circle perimeter: " + circle.perimeter());
System.out.println("Circle area: " + circle.area());
}
}
```
阅读全文