请定义一个Shape类作为抽象类,包含抽象方法计算面积和周长,在通过继承实现至少三个不同形状的子类,程序最终的要求是根据选择的形状,和用户输入的各形状的主要参数,来计算出该形状的周长和面积。
时间: 2024-09-28 15:05:06 浏览: 44
在面向对象编程中,我们可以创建一个抽象类`Shape`来描述所有形状的基本属性和行为。抽象类通常包含一些抽象方法,它们没有具体的实现,而是由其派生类提供。以下是这个例子的一个基本实现:
```java
// 抽象Shape类
public abstract class Shape {
protected String name; // 形状名称
public Shape(String name) {
this.name = name;
}
// 抽象方法,需要子类提供具体实现
public abstract double calculateArea();
public abstract double calculatePerimeter();
// 具体方法
@Override
public String toString() {
return "Name: " + name;
}
}
// 子类,分别表示特定形状
class Circle extends Shape {
private double radius;
public Circle(String name, double radius) {
super(name);
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(String name, double width, double height) {
super(name);
this.width = width;
this.height = height;
}
@Override
public double calculateArea() {
return width * height;
}
@Override
public double calculatePerimeter() {
return 2 * (width + height);
}
}
class Triangle extends Shape {
private double base;
private double height;
public Triangle(String name, double base, double height) {
super(name);
this.base = base;
this.height = height;
}
@Override
public double calculateArea() {
return 0.5 * base * height;
}
@Override
public double calculatePerimeter() {
// 假设三角形有三条等长边
throw new UnsupportedOperationException("Triangle perimeter not implemented");
}
}
```
为了根据用户的输入计算形状的周长和面积,你可以创建一个主函数,让用户选择形状并输入相应的参数:
```java
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose a shape: 1. Circle, 2. Rectangle, 3. Triangle");
int choice = scanner.nextInt();
Shape selectedShape;
switch (choice) {
case 1:
System.out.print("Enter circle's radius: ");
double radius = scanner.nextDouble();
selectedShape = new Circle("Circle", radius);
break;
case 2:
System.out.print("Enter rectangle's width and height: ");
double width = scanner.nextDouble();
double height = scanner.nextDouble();
selectedShape = new Rectangle("Rectangle", width, height);
break;
case 3:
System.out.print("Enter triangle's base and height: ");
double triangleBase = scanner.nextDouble();
double triangleHeight = scanner.nextDouble();
selectedShape = new Triangle("Triangle", triangleBase, triangleHeight);
break;
default:
System.out.println("Invalid choice.");
return;
}
double area = selectedShape.calculateArea();
double perimeter = selectedShape.calculatePerimeter();
System.out.printf("%s has an area of %.2f and a perimeter of %.2f.\n", selectedShape, area, perimeter);
scanner.close();
}
```
阅读全文