定义Shape抽象类,包含私有属性color,创建构造器为color赋值;包含计算周长的方法celPerimeter();定义子类Triangle,包含三边;定义子类Circle,包含半径radius;子类分别实现父类的计算周长功能。代码及运行结果
时间: 2024-05-01 17:17:30 浏览: 99
我了解了您的要求,以下是实现您需求的代码及运行结果:
```java
// Shape抽象类
public abstract class Shape {
private String color;
public Shape(String color) {
this.color = color;
}
public abstract double calcPerimeter();
}
// Triangle子类
public class Triangle extends Shape {
private double a;
private double b;
private double c;
public Triangle(String color, double a, double b, double c) {
super(color);
this.a = a;
this.b = b;
this.c = c;
}
@Override
public double calcPerimeter() {
return a + b + c;
}
}
// Circle子类
public class Circle extends Shape {
private double radius;
public Circle(String color, double radius) {
super(color);
this.radius = radius;
}
@Override
public double calcPerimeter() {
return 2 * Math.PI * radius;
}
}
public class Test {
public static void main(String[] args) {
Triangle t = new Triangle("红色", 3, 4, 5);
System.out.println("三角形的周长为:" + t.calcPerimeter());
Circle c = new Circle("蓝色", 5);
System.out.println("圆形的周长为:" + c.calcPerimeter());
}
}
```
运行结果:
```
三角形的周长为:12.0
圆形的周长为:31.41592653589793
```
阅读全文