请定义一个Shape类作为抽象类,包含抽象方法计算面积和周长,在通过继承实现至少三个不同形状的子类,程序最终的要求是根据选择的形状,和用户输入的各形状的主要参数,来计算出该形状的周长和面积。
时间: 2024-09-27 13:08:32 浏览: 165
首先,我们可以创建一个名为`Shape`的抽象类,它包含两个抽象方法`calculateArea()`和`calculatePerimeter()`,这两个方法用于计算形状的面积和周长。这里是一个简单的定义:
```java
abstract class Shape {
abstract double calculateArea();
abstract double calculatePerimeter();
}
```
接着,我们为`Shape`类创建三个具体的子类,比如`Circle`, `Rectangle`, 和 `Triangle`:
```java
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
double calculateArea() {
return width * height;
}
@Override
double calculatePerimeter() {
return 2 * (width + height);
}
}
class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
double calculateArea() {
return 0.5 * base * height;
}
@Override
double calculatePerimeter() {
// 如果你有特定边长的情况,可以替换这里的计算方式
throw new UnsupportedOperationException("Triangle perimeter requires side lengths");
}
}
```
最后,你可以编写一个主函数来获取用户的输入并调用相应的子类方法来计算周长和面积:
```java
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose a shape:");
System.out.println("1. Circle");
System.out.println("2. Rectangle");
System.out.println("3. Triangle");
int choice = scanner.nextInt();
Shape shape;
switch (choice) {
case 1:
shape = new Circle(scanner.nextDouble());
break;
case 2:
shape = new Rectangle(scanner.nextDouble(), scanner.nextDouble());
break;
case 3:
// 注意,三角形需要用户提供所有边长信息,这里暂未提供
shape = new Triangle(scanner.nextDouble(), scanner.nextDouble());
break;
default:
System.out.println("Invalid choice");
return;
}
System.out.println("Area: " + shape.calculateArea());
System.out.println("Perimeter: " + shape.calculatePerimeter());
scanner.close();
}
```
阅读全文