使用java 设计一个图形类,包括矩形、圆形和三丽形等之类。每个子类都有自己的特定的属性和方法,此如矩形有长和突、原有半径梦,同时每个子类都可以计 算白己的面积和周长
时间: 2024-06-13 15:07:27 浏览: 115
以下是Java中设计的图形类,包括矩形、圆形和三角形等子类,每个子类都有自己的特定属性和方法,同时可以计算自己的面积和周长:
```java
// 定义一个抽象类Shape,包含计算周长和面积的抽象方法
abstract class Shape {
public abstract double getPerimeter();
public abstract double getArea();
}
// 定义矩形类Rectangle,继承自Shape类
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getPerimeter() {
return 2 * (length + width);
}
public double getArea() {
return length * width;
}
}
// 定义圆形类Circle,继承自Shape类
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getPerimeter() {
return 2 * Math.PI * radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
// 定义三角形类Triangle,继承自Shape类
class Triangle extends Shape {
private double a;
private double b;
private double 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;
}
public double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
}
// 定义测试类TestShape,创建各个图形的对象,用参数化构造方法为属性赋值,输出各个图形的周长和面积
public class TestShape {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(3, 4);
Circle circle = new Circle(5);
Triangle triangle = new Triangle(3, 4, 5);
System.out.println("矩形的周长为:" + rectangle.getPerimeter() + ",面积为:" + rectangle.getArea());
System.out.println("圆形的周长为:" + circle.getPerimeter() + ",面积为:" + circle.getArea());
System.out.println("三角形的周长为:" + triangle.getPerimeter() + ",面积为:" + triangle.getArea());
}
}
```
阅读全文