利用接口和两个实现类帮我写一个计算圆和正方形面积的Java代码,接口中要有一个方法两个实现类去重写他,正方形的边长和圆的半径通过键盘输入
时间: 2024-02-12 09:03:38 浏览: 17
好的,以下是实现代码:
```java
import java.util.Scanner;
// 定义形状接口
interface Shape {
double getArea();
}
// 圆形类
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
// 重写getArea方法,计算圆形面积
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
// 正方形类
class Square implements Shape {
private double length;
public Square(double length) {
this.length = length;
}
// 重写getArea方法,计算正方形面积
@Override
public double getArea() {
return length * length;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入圆的半径:");
double radius = scanner.nextDouble();
System.out.print("请输入正方形的边长:");
double length = scanner.nextDouble();
// 创建圆形对象和正方形对象
Circle circle = new Circle(radius);
Square square = new Square(length);
// 调用各自的getArea方法,计算面积并输出
System.out.println("圆的面积为:" + circle.getArea());
System.out.println("正方形的面积为:" + square.getArea());
}
}
```
在上述代码中,我们定义了一个 `Shape` 接口,其中有一个 `getArea` 方法,圆形类和正方形类都实现了这个接口,并分别重写了 `getArea` 方法以计算各自的面积。在 `Main` 类中,我们通过键盘输入圆的半径和正方形的边长,然后创建相应的对象并调用其各自的 `getArea` 方法,计算面积并输出。