用Java实现代码:定义接口,声明若干个abstract方法;创建类,在类中定义若干个参数为接口类型的方法,通过实现接口的类的对象回调类重写的接口方法,实现相应功能
时间: 2024-10-22 11:19:15 浏览: 15
面向对象进阶(抽象类、接口、内部类)例题
在Java中,你可以这样实现多态的概念:
首先,定义一个接口,包含一些抽象方法。例如,我们创建一个名为`Shape`的接口,它有两个抽象方法`draw()`和`calculateArea()`:
```java
public interface Shape {
void draw();
double calculateArea();
}
```
接下来,我们创建两个实现了这个接口的具体类,比如`Circle`和`Rectangle`:
```java
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing a circle...");
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
public class Rectangle implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public void draw() {
System.out.println("Drawing a rectangle...");
}
@Override
public double calculateArea() {
return width * height;
}
}
```
然后,我们可以创建一个类`DrawingBoard`,它有一个`Shape`类型的引用,用于存储各种形状:
```java
public class DrawingBoard {
private Shape shape;
public void setShape(Shape shape) {
this.shape = shape;
}
public void drawShape() {
shape.draw(); // 调用的是shape对象的实际类型的方法
}
public void printArea() {
double area = shape.calculateArea();
System.out.println("The area is: " + area);
}
}
```
现在,你可以这样做来展示多态性:
```java
public static void main(String[] args) {
DrawingBoard board = new DrawingBoard();
Circle circle = new Circle(5.0);
board.setShape(circle);
board.drawShape(); // 输出: Drawing a circle...
board.printArea(); // 输出: The area is: 78.53981633974483
Rectangle rectangle = new Rectangle(10.0, 20.0);
board.setShape(rectangle);
board.drawShape(); // 输出: Drawing a rectangle...
board.printArea(); // 输出: The area is: 200.0
}
```
在这个例子中,`DrawingBoard`并不关心具体的形状是什么,它可以接收任何实现了`Shape`接口的类的实例,并调用它们的方法,这就是多态性的体现。
阅读全文