我给你一个要求和一段代码,你帮我把代码补充完整。要求如下:定义接口或类 Shape,定义求周长的方法length()。 定义如下类,实现接口Shape或父类Shape的方法。 (1)三角形类Triangle (2)长方形类Rectangle (3)圆形类Circle等。 定义测试类ShapeTest,用Shape接口(或类)定义变量shape,用其指向不同类形的对象,输出各种图形的周长。并为其他的Shape接口实现类提供良好的扩展性。 提示: 计算圆周长时PI取3.14。 输入格式: 输入多组数代码如下
时间: 2024-02-21 17:57:41 浏览: 84
Android安卓源码-自定义控件类源代码(18例).zip
代码如下:
```java
interface Shape {
double length();
}
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;
}
public double length() {
return a + b + c;
}
}
class Rectangle implements Shape {
private double width, height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double length() {
return 2 * (width + height);
}
}
class Circle implements Shape {
private double r;
public Circle(double r) {
this.r = r;
}
public double length() {
return 2 * 3.14 * r;
}
}
public class ShapeTest {
public static void main(String[] args) {
Shape shape1 = new Triangle(3, 4, 5);
Shape shape2 = new Rectangle(2, 3);
Shape shape3 = new Circle(1);
System.out.println("三角形周长:" + shape1.length());
System.out.println("长方形周长:" + shape2.length());
System.out.println("圆形周长:" + shape3.length());
}
}
```
阅读全文