定义接口或类 Shape,定义求周长的方法length()。 定义如下类,实现接口Shape或父类Shape的方法。 (1)三角形类Triangle (2)长方形类Rectangle (3)圆形类Circle等。 定义测试类ShapeTest,用Shape接口(或类)定义变量shape,用其指向不同类形的对象,输出各种图形的周长。并为其他的Shape接口实现类提供良好的扩展性。 提示: 计算圆周长时PI取3.14
时间: 2024-03-20 08:44:05 浏览: 61
好的,这是一个关于Java面向对象的问题,下面是一个实现:
首先,我们定义接口Shape:
```java
public interface Shape {
double length();
}
```
接着,我们定义三角形类Triangle:
```java
public class Triangle implements Shape {
private double a, b, c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public double length() {
return a + b + c;
}
}
```
然后,我们定义长方形类Rectangle:
```java
public class Rectangle implements Shape {
private double length, width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double length() {
return 2 * (length + width);
}
}
```
最后,我们定义圆形类Circle:
```java
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double length() {
return 2 * 3.14 * radius;
}
}
```
接下来,我们定义测试类ShapeTest:
```java
public class ShapeTest {
public static void main(String[] args) {
Shape shape1 = new Triangle(3, 4, 5);
System.out.println("Triangle length: " + shape1.length());
Shape shape2 = new Rectangle(3, 4);
System.out.println("Rectangle length: " + shape2.length());
Shape shape3 = new Circle(2);
System.out.println("Circle length: " + shape3.length());
}
}
```
输出结果如下:
```
Triangle length: 12.0
Rectangle length: 14.0
Circle length: 12.56
```
这样,我们就实现了一个简单的形状计算器,并且可以方便地扩展其他的形状类。
阅读全文