参考以下类图提示,完成以下实验任务。 (1)参照类图编写类代码; (2)定义图形抽象类,定义抽象draw方法,并为具体图形类定义具体方法的实 现; (3)设计并定义具体图形面积计算、周长计算方法; (4)编写Test类,测试draw方法。
时间: 2024-04-30 12:23:46 浏览: 93
类图作业
抽象类:
```java
abstract class Shape {
public abstract void draw();
public abstract double calculateArea();
public abstract double calculatePerimeter();
}
```
具体类:
```java
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing a circle with 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(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public void draw() {
System.out.println("Drawing a rectangle with width " + width + " and height " + height);
}
@Override
public double calculateArea() {
return width * height;
}
@Override
public double calculatePerimeter() {
return 2 * (width + height);
}
}
class Triangle extends Shape {
private double a;
private double b;
private double c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public void draw() {
System.out.println("Drawing a triangle with sides " + a + ", " + b + ", and " + c);
}
@Override
public double calculateArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
@Override
public double calculatePerimeter() {
return a + b + c;
}
}
```
测试类:
```java
public class Test {
public static void main(String[] args) {
Shape circle = new Circle(5.0);
circle.draw();
System.out.println("Area: " + circle.calculateArea());
System.out.println("Perimeter: " + circle.calculatePerimeter());
Shape rectangle = new Rectangle(3.0, 4.0);
rectangle.draw();
System.out.println("Area: " + rectangle.calculateArea());
System.out.println("Perimeter: " + rectangle.calculatePerimeter());
Shape triangle = new Triangle(3.0, 4.0, 5.0);
triangle.draw();
System.out.println("Area: " + triangle.calculateArea());
System.out.println("Perimeter: " + triangle.calculatePerimeter());
}
}
```
阅读全文