10、根据要求写代码: (1) 定义Shape抽象类,包含计算周长的抽象方法getPerimeter() (2) 定义子类Triangle,包含三角形的三边属性,重写计算周长方法 (3) 定义子类Circle,包含半径radius,重写计算周长方法 (4) 测试类中实例化两个子类对象,调用计算周长的方法
时间: 2023-11-22 09:56:21 浏览: 62
```java
// Shape抽象类
public abstract class Shape {
public abstract double getPerimeter();
}
// Triangle子类
public class Triangle extends 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 getPerimeter() {
return a + b + c;
}
}
// Circle子类
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
// 测试类
public class Test {
public static void main(String[] args) {
Triangle triangle = new Triangle(3, 4, 5);
System.out.println("三角形周长:" + triangle.getPerimeter());
Circle circle = new Circle(2);
System.out.println("圆的周长:" + circle.getPerimeter());
}
}
```
阅读全文