定义一个抽象类 Shape,其中包含求形状的面积和周长的抽象方法。定义三角形、矩形、圆形类,继承Shape。分别创建一个三角形、矩形、圆形对象,输出各类图形的面积和周长。三角形是常规三角形。JAVA
时间: 2024-10-11 19:03:51 浏览: 129
首先,在Java中,你可以通过定义一个抽象类`Shape`来实现多态和抽象方法的概念。抽象类不能实例化,它通常包含一些抽象方法,这些方法没有具体实现,需要在它的子类中提供。以下是代码的一个例子:
```java
// 定义抽象类 Shape
abstract class Shape {
abstract double getArea(); // 抽象方法,计算面积
abstract double getPerimeter(); // 抽象方法,计算周长
// 具体方法,打印信息
void printDetails() {
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() {
// 仅举一例,实际取决于三角形的具体类型
return base + Math.sqrt(Math.pow(height, 2) + Math.pow(base / 2, 2));
}
@Override
void printDetails() {
System.out.println("Triangle with base " + base + " and height " + 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 printDetails() {
System.out.println("Rectangle with width " + width + " and length " + 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 printDetails() {
System.out.println("Circle with radius " + radius);
}
}
// 创建对象并输出信息
public static void main(String[] args) {
Triangle triangle = new Triangle(3, 4);
rectangle = new Rectangle(5, 6);
circle = new Circle(2);
triangle.printDetails();
System.out.println("Triangle area: " + triangle.getArea());
System.out.println("Triangle perimeter: " + triangle.getPerimeter());
rectangle.printDetails();
System.out.println("Rectangle area: " + rectangle.getArea());
System.out.println("Rectangle perimeter: " + rectangle.getPerimeter());
circle.printDetails();
System.out.println("Circle area: " + circle.getArea());
System.out.println("Circle perimeter: " + circle.getPerimeter());
}
```
阅读全文