定一个抽象类为Shape ,它包括抽象方法有计算面积、求周长,Shape类派生子类有Rectangle、Circle和Triangle类,用Java编写实现求它们的面积和周长。
时间: 2024-11-09 08:27:44 浏览: 58
在Java中,你可以使用抽象类(Abstract Class)和接口(Interface)来定义一个通用的形状模板,然后让Rectangle、Circle和Triangle等具体形状类继承或实现这个模板。这里我会先介绍如何定义抽象类和抽象方法,然后展示如何创建具体的子类。
首先,我们定义一个名为`Shape`的抽象类,包含两个抽象方法`getArea()`和`getCircumference()`:
```java
public abstract class Shape {
// 定义抽象方法
public abstract double getArea();
public abstract double getCircumference();
// 具体的方法实现可以放在这里,因为Shape是抽象的
public String getName() {
return getClass().getSimpleName();
}
}
```
接下来,我们创建`Rectangle`, `Circle`, 和 `Triangle` 类,它们分别继承自`Shape` 并实现抽象方法:
```java
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
@Override
public double getCircumference() {
return 2 * (width + height);
}
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * Math.pow(radius, 2);
}
@Override
public double getCircumference() {
return 2 * Math.PI * radius;
}
}
public class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double getArea() {
return 0.5 * base * height;
}
@Override
public double getCircumference() {
// 三角形没有周长,此处返回不适用的值
throw new UnsupportedOperationException("Circumference not applicable for a triangle.");
}
}
```
现在你已经有一个基础的框架,可以根据这些类来创建实例并调用它们的面积和周长方法:
```java
public static void main(String[] args) {
Shape rectangle = new Rectangle(5, 10);
Shape circle = new Circle(7);
Shape triangle = new Triangle(6, 4);
System.out.println(rectangle.getName() + " area: " + rectangle.getArea());
System.out.println(circle.getName() + " area: " + circle.getArea());
System.out.println(triangle.getName() + " area: " + triangle.getArea());
// 注意:三角形没有周长
System.out.println(rectangle.getName() + " circumference: " + rectangle.getCircumference());
System.out.println(circle.getName() + " circumference: " + circle.getCircumference());
}
```
阅读全文