现有一个接口Shape,该接口有someutererimeter和comeuteacea两个方法。有三个类:circle类(圆形)、Rectangle类(矩形)、Triangle类(三角形)对Shape进行实现,分别实现对以上三种形状的周长和面积的计算。请根据LSP写出代码
时间: 2024-09-28 09:11:40 浏览: 34
在遵循里氏替换原则(Liskov Substitution Principle,简称LSP)的情况下,我们需要保证子类能够替换掉它们的父类而不影响程序的预期行为。在这个例子中,`Shape`接口是父类,`Circle`, `Rectangle`, 和 `Triangle` 类都是其子类。每个子类都应提供它们特有的周长和面积计算方法,并且这些方法的行为应该符合接口中定义的方法签名。
这里是一个简单的Java示例:
```java
// Shape接口
interface Shape {
double calculatePerimeter();
double calculateArea();
}
// Circle类实现Shape接口
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
// Rectangle类实现Shape接口
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 calculatePerimeter() {
return 2 * (width + height);
}
@Override
public double calculateArea() {
return width * height;
}
}
// Triangle类实现Shape接口
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 calculatePerimeter() {
return base + base + Math.sqrt(Math.pow(height, 2) / 4);
}
// 根据海伦公式计算面积
@Override
public double calculateArea() {
double s = (base + base + Math.sqrt(Math.pow(height, 2) / 4)) / 2;
return Math.sqrt(s * (s - base) * (s - base) * (s - Math.sqrt(Math.pow(height, 2) / 4)));
}
}
// 使用场景
public class Main {
public static void main(String[] args) {
Shape shape1 = new Circle(5); // 圆形实例
Shape shape2 = new Rectangle(3, 4); // 矩形实例
Shape shape3 = new Triangle(6, 8); // 三角形实例
System.out.println("Circle perimeter: " + shape1.calculatePerimeter());
System.out.println("Circle area: " + shape1.calculateArea());
System.out.println("Rectangle perimeter: " + shape2.calculatePerimeter());
System.out.println("Rectangle area: " + shape2.calculateArea());
System.out.println("Triangle perimeter: " + shape3.calculatePerimeter());
System.out.println("Triangle area: "
阅读全文