用java 定义一个抽象类 Shape,其中包含求形状的面积和周长的抽象方法。定义三角形、矩形、圆形类,继承Shape。分别创建一个三角形、矩形、圆形对象,输出各类图形的面积和周长。
时间: 2024-10-05 13:03:58 浏览: 84
在Java中,我们可以这样定义一个抽象类`Shape`以及它的派生类:
```java
// 抽象Shape类
abstract class Shape {
// 抽象方法,声明计算面积和周长的行为
abstract double getArea();
abstract double getPerimeter();
// 打印通用信息
void displayInfo() {
System.out.println("This is an abstract shape.");
}
}
// 三角形类,继承Shape并实现抽象方法
class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
double getArea() {
return 0.5 * base * height;
}
@Override
double getPerimeter() {
// 假设这是一个等腰三角形,有两条边相等
double side = base / 2;
return side + base + side;
}
@Override
void displayInfo() {
super.displayInfo();
System.out.printf("Base: %f, Height: %f\n", base, height);
}
}
// 矩形类,继承Shape并实现抽象方法
class Rectangle extends Shape {
private double width;
private double length;
public Rectangle(double width, double length) {
this.width = width;
this.length = length;
}
@Override
double getArea() {
return width * length;
}
@Override
double getPerimeter() {
return 2 * (width + length);
}
@Override
void displayInfo() {
super.displayInfo();
System.out.printf("Width: %f, Length: %f\n", width, length);
}
}
// 圆形类,继承Shape并实现抽象方法
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
double getArea() {
return Math.PI * Math.pow(radius, 2);
}
@Override
double getPerimeter() {
return 2 * Math.PI * radius;
}
@Override
void displayInfo() {
super.displayInfo();
System.out.printf("Radius: %f\n", radius);
}
}
public class Main {
public static void main(String[] args) {
// 创建实例并打印信息
Triangle triangle = new Triangle(5, 6);
rectangle = new Rectangle(4, 8);
Circle circle = new Circle(3);
triangle.displayInfo();
System.out.println("Triangle area: " + triangle.getArea());
System.out.println("Triangle perimeter: " + triangle.getPerimeter());
rectangle.displayInfo();
System.out.println("Rectangle area: " + rectangle.getArea());
System.out.println("Rectangle perimeter: " + rectangle.getPerimeter());
circle.displayInfo();
System.out.println("Circle area: " + circle.getArea());
System.out.println("Circle perimeter: " + circle.getPerimeter());
}
}
```
当你运行这个`Main`类,它会分别计算并显示每个图形的面积和周长。
阅读全文