用java3.对2中的代码进行修改,将Shape类改为接口,三角形类和圆形类实现Shape接口,主类中测试这些类和接口的使用,体现出多态性。
时间: 2023-06-12 08:06:40 浏览: 54
好的,以下是修改后的代码:
```java
// Shape 接口
interface Shape {
double getArea();
}
// Triangle 类实现 Shape 接口
class Triangle implements Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double getArea() {
return 0.5 * base * height;
}
}
// Circle 类实现 Shape 接口
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
// 主类
public class Main {
public static void main(String[] args) {
Shape t = new Triangle(10, 5);
System.out.println("三角形的面积为:" + t.getArea());
Shape c = new Circle(5);
System.out.println("圆形的面积为:" + c.getArea());
}
}
```
以上代码中,我们将 `Shape` 类改为了 `Shape` 接口,并让 `Triangle` 和 `Circle` 类实现了 `Shape` 接口。在 `Main` 主类中,我们分别创建了一个 `Triangle` 对象和一个 `Circle` 对象,并将它们赋值给 `Shape` 类型的变量 `t` 和 `c`。这里我们体现了多态性,即一个父类(或接口)类型的变量可以引用不同子类(或实现类)类型的对象。最后,我们分别调用了 `getArea()` 方法,得到了三角形和圆形的面积。