用java定义一个图形Shape类,包含三个抽象方法:求周长calPerimeter()、返回图形类型getType()以及求面积getArea();再分别定义一个三角形类、圆形类、矩形类继承Shape类,并实现相应的抽象方法;最后编写一个测试类,分别创建相应类的实例对象,测试方法
时间: 2023-05-15 19:05:02 浏览: 174
设计一个抽象类图形类,在该类中包含有至少两个抽象方法求周长和求面积,分别定义圆形类、长方形类、正方形类、三角形类来继承图形类,并实现上述两个方法
5星 · 资源好评率100%
好的,以下是我为您准备的代码:
```
// Shape类
abstract class Shape {
public abstract double calPerimeter();
public abstract String getType();
public abstract double getArea();
}
// Triangle类
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 calPerimeter() {
return a + b + c;
}
public String getType() {
return "Triangle";
}
public double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
}
// Circle类
class Circle extends Shape {
private double r;
public Circle(double r) {
this.r = r;
}
public double calPerimeter() {
return 2 * Math.PI * r;
}
public String getType() {
return "Circle";
}
public double getArea() {
return Math.PI * r * r;
}
}
// Rectangle类
class Rectangle extends Shape {
private double width, height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double calPerimeter() {
return 2 * (width + height);
}
public String getType() {
return "Rectangle";
}
public double getArea() {
return width * height;
}
}
// 测试类
public class Test {
public static void main(String[] args) {
Shape triangle = new Triangle(3, 4, 5);
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(3, 4);
System.out.println(triangle.getType() + " perimeter: " + triangle.calPerimeter() + ", area: " + triangle.getArea());
System.out.println(circle.getType() + " perimeter: " + circle.calPerimeter() + ", area: " + circle.getArea());
System.out.println(rectangle.getType() + " perimeter: " + rectangle.calPerimeter() + ", area: " + rectangle.getArea());
}
}
```
希望这份代码能够满足您的需求。
阅读全文