参照样例程序 6,用接口的方式改写样例程序 5,编写常见的图形类及其成员,请使用 多态表达其绘制方法。
时间: 2024-02-13 13:02:04 浏览: 17
以下是使用接口和多态来实现常见图形类的示例代码:
```
interface Shape {
void draw();
}
class Circle implements Shape {
public void draw() {
System.out.println("Drawing a circle.");
}
}
class Rectangle implements Shape {
public void draw() {
System.out.println("Drawing a rectangle.");
}
}
class Triangle implements Shape {
public void draw() {
System.out.println("Drawing a triangle.");
}
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Circle(), new Rectangle(), new Triangle() };
for (Shape shape : shapes) {
shape.draw();
}
}
}
```
在上面的程序中,我们定义了一个 Shape 接口,包含一个 draw() 方法。然后我们定义了三个图形类 Circle、Rectangle 和 Triangle,它们实现了 Shape 接口,并重写了 draw() 方法。在主函数中,我们创建了一个 Shape 类型的数组,包含三个不同的图形对象,然后通过多态调用每个图形对象的 draw() 方法,实现了对不同图形的绘制。输出结果为:
```
Drawing a circle.
Drawing a rectangle.
Drawing a triangle.
```