Java 利用接口设计和实现oval和rectangle.
时间: 2023-05-11 09:07:29 浏览: 112
可以使用接口来设计和实现 Oval 和 Rectangle 类。首先,定义一个 Shape 接口,其中包含计算面积和周长的方法。然后,定义 Oval 和 Rectangle 类,它们都实现 Shape 接口,并实现自己的计算面积和周长的方法。以下是示例代码:
```
interface Shape {
double getArea();
double getPerimeter();
}
class Oval implements Shape {
private double a;
private double b;
public Oval(double a, double b) {
this.a = a;
this.b = b;
}
@Override
public double getArea() {
return Math.PI * a * b;
}
@Override
public double getPerimeter() {
return 2 * Math.PI * Math.sqrt((a * a + b * b) / 2);
}
}
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 getArea() {
return width * height;
}
@Override
public double getPerimeter() {
return 2 * (width + height);
}
}
```
阅读全文