1.编写一个抽象类(Shape),长方形、三角形和圆形均为其子类,并各有各的属性。其父类中有计算周长和面积的方法。在测试类中,分别建立如干个对象,计算并输出各对象的周长和面积。
时间: 2024-12-24 17:28:55 浏览: 1
首先,我们可以创建一个名为`Shape`的抽象类,作为所有形状的基础类型。这个抽象类将包含一些通用的属性,如`color`,以及两个抽象方法`calculatePerimeter`和`calculateArea`,表示计算周长和面积的行为:
```java
abstract class Shape {
String color;
abstract double calculatePerimeter();
abstract double calculateArea();
// 构造函数可以设置颜色等实例变量
public Shape(String color) {
this.color = color;
}
}
// 具体的子类,比如Rectangle, Triangle和Circle
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(String color, double length, double width) {
super(color);
this.length = length;
this.width = width;
}
@Override
double calculatePerimeter() {
return 2 * (length + width);
}
@Override
double calculateArea() {
return length * width;
}
}
class Triangle extends Shape {
private double base;
private double height;
public Triangle(String color, double base, double height) {
super(color);
this.base = base;
this.height = height;
}
@Override
double calculatePerimeter() {
// 实现三角形周长计算...
}
@Override
double calculateArea() {
// 实现三角形面积计算...
}
}
class Circle extends Shape {
private double radius;
public Circle(String color, double radius) {
super(color);
this.radius = radius;
}
@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
}
```
然后,在测试类`Main`中,你可以创建这些形状的对象,计算它们的周长和面积,然后打印出来:
```java
public class Main {
public static void main(String[] args) {
Shape rectangle = new Rectangle("blue", 5, 7);
Shape triangle = new Triangle("red", 4, 6);
Shape circle = new Circle("green", 3);
System.out.println("Rectangle perimeter: " + rectangle.calculatePerimeter());
System.out.println("Rectangle area: " + rectangle.calculateArea());
System.out.println("Triangle perimeter: " + triangle.calculatePerimeter());
System.out.println("Triangle area: " + triangle.calculateArea());
System.out.println("Circle perimeter: " + circle.calculatePerimeter());
System.out.println("Circle area: " + circle.calculateArea());
}
}
```
阅读全文