定义一个抽象类Shape,它包含一个抽象方法getArea0,从Shape类派生出Rectangle和 Cirele类,这两个类都用getArea0方法计算对象的面积。编写测试类创建Rectangle和 Circle对象,并分别打印输出它们的面积:
时间: 2024-02-17 16:00:59 浏览: 102
编写一个抽象类Shape
4星 · 用户满意度95%
好的,下面是代码实现:
```java
// Shape.java
public abstract class Shape {
public abstract double getArea0();
}
// Rectangle.java
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
@Override
public double getArea0() {
return width * height;
}
}
// Circle.java
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
@Override
public double getArea0() {
return Math.PI * radius * radius;
}
}
// Test.java
public class Test {
public static void main(String[] args) {
Shape rect = new Rectangle(5, 8);
System.out.println("Rectangle Area: " + rect.getArea0());
Shape circle = new Circle(4);
System.out.println("Circle Area: " + circle.getArea0());
}
}
```
输出结果为:
```
Rectangle Area: 40.0
Circle Area: 50.26548245743669
```
阅读全文