java编写一个使用接口的简单代码
时间: 2024-04-17 19:25:05 浏览: 19
当然,我可以为您提供一个简单的示例代码,演示如何在Java中使用接口。
```java
// 定义一个接口
interface Shape {
double getArea();
double getPerimeter();
}
// 实现接口的类 - 圆形
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
// 实现接口的类 - 矩形
class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getArea() {
return length * width;
}
public double getPerimeter() {
return 2 * (length + width);
}
}
// 主程序
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(5.0);
System.out.println("圆形的面积:" + circle.getArea());
System.out.println("圆形的周长:" + circle.getPerimeter());
Shape rectangle = new Rectangle(4.0, 6.0);
System.out.println("矩形的面积:" + rectangle.getArea());
System.out.println("矩形的周长:" + rectangle.getPerimeter());
}
}
```
在上述代码中,我们定义了一个`Shape`接口,其中包含了`getArea()`和`getPerimeter()`两个方法。然后,我们创建了两个实现了`Shape`接口的类:`Circle`和`Rectangle`。最后,在主程序中,我们创建了一个圆形对象和一个矩形对象,并调用它们的方法来计算面积和周长。
希望这个示例能够帮助您理解如何在Java中使用接口。如果有任何问题,请随时提问!