设计Shape、Square、Circle 3个类,计算周长和面积,编写ShapeTest类创建子类对象和输出其周长、面积。
时间: 2024-10-08 22:02:45 浏览: 33
设计这个场景,我们可以创建一个抽象父类`Shape`,然后有两个具体的子类`Square`和`Circle`,每个子类都覆盖`Shape`的`calculatePerimeter`和`calculateArea`方法。这里是一个简单的Java代码示例:
```java
// Shape抽象类
abstract class Shape {
abstract double calculatePerimeter();
abstract double calculateArea();
// 打印信息的方法
void printInfo() {
System.out.println("This is a shape.");
}
}
// Square类,实现了Shape
class Square extends Shape {
private double side;
public Square(double side) {
this.side = side;
}
@Override
double calculatePerimeter() {
return 4 * side;
}
@Override
double calculateArea() {
return side * side;
}
@Override
void printInfo() {
super.printInfo();
System.out.printf("Side length: %.2f\n", side);
System.out.println("Perimeter: %.2f\n", calculatePerimeter());
System.out.println("Area: %.2f\n", calculateArea());
}
}
// Circle类,也实现了Shape
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
@Override
void printInfo() {
super.printInfo();
System.out.printf("Radius: %.2f\n", radius);
System.out.println("Circumference: %.2f\n", calculatePerimeter());
System.out.println("Area: %.2f\n", calculateArea());
}
}
// ShapeTest类用于测试
public class ShapeTest {
public static void main(String[] args) {
Shape square = new Square(5);
square.printInfo();
Shape circle = new Circle(3);
circle.printInfo();
}
}
```
在这个例子中,`ShapeTest`类通过创建`Square`和`Circle`的对象并调用它们的`printInfo`方法,展示了各自形状的周长和面积。
阅读全文