public interface使用的代码案例
时间: 2024-05-06 20:21:47 浏览: 9
好的,我明白了。关于你的问题,我可以提供一个简单的public interface使用的Java代码案例:
```
public interface Shape {
double calculateArea();
}
public class Rectangle implements Shape {
private double length, width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double calculateArea() {
return length * width;
}
}
public class Circle implements Shape {
private double radius;
private final double PI = 3.14;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
Shape shape1 = new Rectangle(5, 10);
System.out.println("The area of the rectangle is: " + shape1.calculateArea());
Shape shape2 = new Circle(7);
System.out.println("The area of the circle is: " + shape2.calculateArea());
}
}
```
这个案例演示了一个public interface的使用,interface被命名为Shape。有两个类Rectangle和Circle分别实现了Shape接口,并实现了Shape接口中定义的方法calculateArea()。在Main类中,我们使用Shape接口来创建shape1和shape2对象,并分别调用它们的calculateArea()方法来计算面积。希望这个案例能满足你的需求。