编写一个Java程序,在程序中定义一个抽象类Shape,包含两个抽象方法,一个是计算面积 area() ,一个是显示面积 showArea(),再定义Shape类的两个子类 Rectangle 类和 Circle 类,设计一个程序,输出矩形和圆的面积
时间: 2024-02-09 18:09:46 浏览: 27
好的,这是一个简单的Java程序,用于计算矩形和圆的面积:
```java
abstract class Shape {
abstract double area();
abstract void showArea();
}
class Rectangle extends Shape {
double width, height;
Rectangle(double w, double h) {
width = w;
height = h;
}
double area() {
return width * height;
}
void showArea() {
System.out.println("矩形面积为:" + area());
}
}
class Circle extends Shape {
double radius;
Circle(double r) {
radius = r;
}
double area() {
return Math.PI * radius * radius;
}
void showArea() {
System.out.println("圆面积为:" + area());
}
}
public class Main {
public static void main(String[] args) {
Shape s1 = new Rectangle(3, 4);
Shape s2 = new Circle(5);
s1.showArea();
s2.showArea();
}
}
```
程序输出:
```
矩形面积为:12.0
圆面积为:78.53981633974483
```
阅读全文