使用抽象方法和抽象类,编程实现图5.3所示的类层次图,并给出一个运行结果。
时间: 2024-02-22 09:00:27 浏览: 24
好的,下面是代码实现:
```
//抽象类
abstract class Shape {
public abstract double getArea();
public abstract double getPerimeter();
}
//具体类
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getPerimeter() {
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;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
}
public class Test {
public static void main(String[] args) {
Shape shape1 = new Circle(5);
Shape shape2 = new Rectangle(3, 4);
System.out.println("圆形的面积为:" + shape1.getArea() + ",周长为:" + shape1.getPerimeter());
System.out.println("矩形的面积为:" + shape2.getArea() + ",周长为:" + shape2.getPerimeter());
}
}
```
在这个示例代码中,我们定义了一个抽象类 Shape,其中有两个抽象方法 getArea() 和 getPerimeter()。Circle 和 Rectangle 类分别继承了 Shape 类,并实现了它的抽象方法。在 Test 类中,我们创建了一个 Circle 对象和一个 Rectangle 对象,然后分别调用它们的 getArea() 和 getPerimeter() 方法。
运行结果为:
```
圆形的面积为:78.53981633974483,周长为:31.41592653589793
矩形的面积为:12.0,周长为:14.0
```
这个示例代码展示了如何使用抽象类和抽象方法来实现类层次图。我们可以通过继承抽象类 Shape,并实现它的抽象方法来创建具体的图形类。同时,由于 Shape 类是抽象的,我们不能直接实例化它,只能通过它的具体子类来创建对象。