2.定义抽象类Shape,抽象方法为showArea(),求出面积并显示,定义矩形类Rectangle,正方形类Square,圆类 Circle,根据各自的属性,用showArea方法求出各自的面积,在main方法中构造3个对象,调用showArea方法。程序
时间: 2023-07-31 18:05:22 浏览: 249
```java
// Shape.java
public abstract class Shape {
public abstract void showArea();
}
// Rectangle.java
public class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public void showArea() {
double area = length * width;
System.out.println("The area of the rectangle is " + area);
}
}
// Square.java
public class Square extends Shape {
private double side;
public Square(double side) {
this.side = side;
}
@Override
public void showArea() {
double area = side * side;
System.out.println("The area of the square is " + area);
}
}
// Circle.java
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public void showArea() {
double area = Math.PI * radius * radius;
System.out.println("The area of the circle is " + area);
}
}
// Main.java
public class Main {
public static void main(String[] args) {
Shape rect = new Rectangle(10, 20);
Shape square = new Square(5);
Shape circle = new Circle(3);
rect.showArea();
square.showArea();
circle.showArea();
}
}
```
输出结果:
```
The area of the rectangle is 200.0
The area of the square is 25.0
The area of the circle is 28.274333882308138
```
阅读全文