用eclipse实现定义抽象类Shape及其子类矩形Rect类和圆形Ciecle类,在main()实现实例化子类,键盘输入半径的值,输出宽=4,高=4的矩形面积,键盘输入半径的值,输出圆的面积,小数位数默认,所有计算均通过调用类的
时间: 2024-05-04 14:22:19 浏览: 113
方法实现。
以下是示例代码:
```java
// Shape.java
public abstract class Shape {
public abstract double getArea();
}
// Rect.java
public class Rect extends Shape {
private double width;
private double height;
public Rect(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
// Circle.java
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
// Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 实例化矩形对象并计算面积
Rect rect = new Rect(4, 4);
System.out.println("矩形面积为:" + rect.getArea());
// 实例化圆形对象并计算面积
System.out.print("请输入圆的半径:");
double radius = scanner.nextDouble();
Circle circle = new Circle(radius);
System.out.println("圆的面积为:" + circle.getArea());
scanner.close();
}
}
```
运行结果:
```
矩形面积为:16.0
请输入圆的半径:5
圆的面积为:78.53981633974483
```
阅读全文