酷代码 AI
菜单
服务商

上转型对象与多态:定义一个基类shape,包含一个方法area(),返回0。定义两个子类rectangle和circle,重写area()方法,分别返回计算后的面积值。创建shape数组,存储不同形状的对象并计算每个形状的面积,进行输出。java实现

```java // 定义基类 Shape class Shape { public double area() { return 0; } } // 定义子类 Rectangle 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 area() { return width * height; } } // 定义子类 Circle class Circle extends Shape { private double radius; public Circle(double radius) { this.radius = radius; } @Override public double area() { return Math.PI * radius * radius; } } public class Main { public static void main(String[] args) { // 创建 shape 数组,存储不同形状的对象 Shape[] shapes = new Shape[3]; shapes[0] = new Rectangle(3, 4); shapes[1] = new Circle(5); shapes[2] = new Rectangle(2, 6); // 计算每个形状的面积并进行输出 for (int i = 0; i < shapes.length; i++) { System.out.println("Shape " + (i + 1) + " area: " + shapes[i].area()); } } } ``` 运行结果: ``` Shape 1 area: 12.0 Shape 2 area: 78.53981633974483 Shape 3 area: 12.0 ``` [2024-10-21 08:39:49 | AI写代码神器 | 806点数解答]

相关提问
实用工具查看更多
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]
数独游戏 [娱乐类]
经典推箱子 [娱乐类]
AI摸鱼五子棋 [娱乐类]