定义Shape类表示一般二维图形。Shape具有抽象方法area和perimeter,分别计算形状的面积和周长。试定义二维形状类矩形、三角形、圆形,这些均为Shape类的子类,并计算出这些形状的面积和周长,打印输出相关信息。用JAVA写
时间: 2024-12-17 10:17:15 浏览: 6
java代码-求面积和周长
首先,我们定义一个名为`Shape`的抽象类,包含两个抽象方法`area()`和`perimeter()`,代表通用的面积和周长计算:
```java
import java.util.Random;
abstract class Shape {
abstract double area();
abstract double perimeter();
public void printInfo() {
System.out.println("Shape Information:");
System.out.println("Area: " + area());
System.out.println("Perimeter: " + perimeter());
}
}
```
接下来,我们会创建三个具体的形状子类:`Rectangle`, `Triangle`, 和 `Circle`,它们分别覆盖`Shape`的抽象方法:
```java
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
double area() {
return length * width;
}
@Override
double perimeter() {
return 2 * (length + width);
}
@Override
public void printInfo() {
super.printInfo();
System.out.println("Rectangle: Length = " + length + ", Width = " + width);
}
}
class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
double area() {
return 0.5 * base * height;
}
@Override
double perimeter() {
// 这里假设是等腰三角形,如果有不同类型三角形需要提供对应方法
double side = Math.random(); // 假设边长为随机数
return side + base + side;
}
@Override
public void printInfo() {
super.printInfo();
System.out.println("Triangle: Base = " + base + ", Height = " + height);
}
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * Math.pow(radius, 2);
}
@Override
double perimeter() {
return 2 * Math.PI * radius;
}
@Override
public void printInfo() {
super.printInfo();
System.out.println("Circle: Radius = " + radius);
}
}
public class Main {
public static void main(String[] args) {
Random random = new Random();
Shape rectangle = new Rectangle(5, 7);
Shape triangle = new Triangle(random.nextDouble(), random.nextDouble());
Shape circle = new Circle(random.nextDouble());
rectangle.printInfo();
triangle.printInfo();
circle.printInfo();
}
}
```
这个程序会生成并打印每个形状的面积和周长,以及其特定属性,如矩形的长度和宽度、三角形的底和高、以及圆的半径。
阅读全文