定义Shape抽象类,包含私有属性color,创建构造器为color赋值;包含计算周长的方法celPerimeter();定义子类Triangle,包含三边;定义子类Circle,包含半径radius;子类分别实现父类的计算周长功能。
时间: 2024-05-08 07:20:38 浏览: 156
下面是代码实现:
```java
// Shape.java
public abstract class Shape {
private String color;
public Shape(String color) {
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public abstract double calcPerimeter();
}
// Triangle.java
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;
}
public double getA() {
return a;
}
public void setA(double a) {
this.a = a;
}
public double getB() {
return b;
}
public void setB(double b) {
this.b = b;
}
public double getC() {
return c;
}
public void setC(double c) {
this.c = c;
}
@Override
public double calcPerimeter() {
return a + b + c;
}
}
// Circle.java
public class Circle extends Shape {
private double radius;
public Circle(String color, double radius) {
super(color);
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
@Override
public double calcPerimeter() {
return 2 * Math.PI * radius;
}
}
```
使用示例:
```java
Triangle triangle = new Triangle("Red", 3, 4, 5);
System.out.println(triangle.getColor() + "三角形的周长为:" + triangle.calcPerimeter());
Circle circle = new Circle("Blue", 2.0);
System.out.println(circle.getColor() + "圆形的周长为:" + circle.calcPerimeter());
```
阅读全文