定义一个抽象类Shape,它包含一个抽象方法getArea(),从Shape类派生出Rectangle和Circle类,这两个类都用getArea()方法计算对象的面积。编写应用程序使用Rectang...
时间: 2024-03-12 18:45:28 浏览: 29
好的,这是一个很基础的面向对象编程的问题。以下是一个可能的解决方案:
```java
// 定义抽象类Shape
abstract class Shape {
// 声明抽象方法getArea()
public abstract double getArea();
}
// 定义Rectangle类
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double w, double h) {
this.width = w;
this.height = h;
}
// 实现getArea()方法,计算矩形面积
@Override
public double getArea() {
return this.width * this.height;
}
}
// 定义Circle类
class Circle extends Shape {
private double radius;
public Circle(double r) {
this.radius = r;
}
// 实现getArea()方法,计算圆形面积
@Override
public double getArea() {
return Math.PI * this.radius * this.radius;
}
}
// 编写应用程序
public class Main {
public static void main(String[] args) {
// 创建一个矩形对象
Rectangle rect = new Rectangle(3, 4);
// 计算矩形面积并输出结果
System.out.println("矩形的面积是:" + rect.getArea());
// 创建一个圆形对象
Circle circle = new Circle(5);
// 计算圆形面积并输出结果
System.out.println("圆形的面积是:" + circle.getArea());
}
}
```
在这个例子中,我们定义了一个抽象类Shape,其中包含一个抽象方法getArea()。然后我们从Shape类派生出了Rectangle和Circle类,并在这两个类中实现了getArea()方法,用于计算对象的面积。在应用程序中,我们创建了一个矩形对象和一个圆形对象,并分别调用它们的getArea()方法来计算它们的面积。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)