通过接口引用对象

在Java中,通过接口引用对象是一种多态的应用,它允许使用接口类型的引用来引用实现了该接口的对象。这有助于编写更灵活、可扩展的代码。下面是一个简单的例子,展示了如何通过接口引用对象:

假设有一个接口 Drawable

// 接口
interface Drawable {
    void draw();
}

// 实现接口的类
class Circle implements Drawable {
    @Override
    public void draw() {
        System.out.println("Drawing a Circle");
    }
}

class Square implements Drawable {
    @Override
    public void draw() {
        System.out.println("Drawing a Square");
    }
}

现在,我们可以通过接口 Drawable 来引用不同的实现类的对象:

public class Main {
    public static void main(String[] args) {
        // 通过接口引用对象
        Drawable circle = new Circle();
        Drawable square = new Square();

        // 调用 draw 方法,实际调用的是具体对象的 draw 方法
        circle.draw(); // 输出: Drawing a Circle
        square.draw(); // 输出: Drawing a Square

        // 使用数组存储不同的 Drawable 对象
        Drawable[] shapes = new Drawable[]{circle, square};

        // 循环调用 draw 方法
        for (Drawable shape : shapes) {
            shape.draw();
        }
        // 输出:
        // Drawing a Circle
        // Drawing a Square
    }
}

在这个例子中,Drawable 接口定义了一个 draw 方法,而 CircleSquare 类都实现了这个接口。通过使用接口类型的引用,我们可以在运行时指定具体的对象类型,实现了多态性。这使得代码更加灵活,能够轻松地替换和添加新的实现类,而不需要修改使用这些对象的代码。

相关推荐

  1. 通过接口引用对象

    2023-12-17 16:58:03       36 阅读
  2. linux下tcp/udp协议网络通信接口封装+日志打印对象

    2023-12-17 16:58:03       14 阅读
  3. js中原始类型和对象引用

    2023-12-17 16:58:03       30 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-17 16:58:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-17 16:58:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-17 16:58:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-17 16:58:03       20 阅读

热门阅读

  1. 一句话分清C/C++声明和定义

    2023-12-17 16:58:03       41 阅读
  2. Vue3源码梳理:响应式系统的前世今生

    2023-12-17 16:58:03       35 阅读
  3. 数据库处理与分组存储

    2023-12-17 16:58:03       30 阅读
  4. MySQL数据库的特点、语法、指令...

    2023-12-17 16:58:03       35 阅读
  5. AIGC stable diffusion学习笔记

    2023-12-17 16:58:03       39 阅读
  6. Golang 二分查找 LEETCODE704 小记

    2023-12-17 16:58:03       48 阅读
  7. css前端主题切换方案(三种)

    2023-12-17 16:58:03       30 阅读
  8. C语言经典错误总结(三)

    2023-12-17 16:58:03       39 阅读
  9. 在Flutter中使用PhotoViewGallery指南

    2023-12-17 16:58:03       40 阅读
  10. 【Qt5】QMouseEvent的globalPos

    2023-12-17 16:58:03       38 阅读