(2)在Shape 类基础上设计圆形、矩形子类,要求根据实际形状重写getArea()方法,并设计一个TestShape 类,通过调用countArea方法把两个对象面积累加到area中,最后输出area.
时间: 2024-10-25 18:09:33 浏览: 21
首先,我们基于`Shape`类创建`Circle`和`Rectangle`子类,这两个类都重写了`gctArea()`方法并将其命名为`getArea()`以保持命名一致性:
```java
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
```
接下来,我们设计一个`TestShape`类,它有一个方法`countArea`用于统计两个形状的总面积:
```java
public class TestShape {
private double area;
public void countArea(Shape shape1, Shape shape2) {
area += shape1.getArea();
area += shape2.getArea();
}
public void displayArea() {
System.out.println("Total area: " + area);
}
}
```
现在,你可以实例化`Circle`和`Rectangle`,并将它们传递给`TestShape`来测试面积累加:
```java
public static void main(String[] args) {
Circle circle = new Circle(5.0);
Rectangle rectangle = new Rectangle(4.0, 6.0);
TestShape test = new TestShape();
test.countArea(circle, rectangle);
test.displayArea();
}
```
阅读全文