首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 閉包與回調機制深度解析:內部類實現模式

     編輯:Java 相關知識

什麼是閉包?

閉包是一個可調用對象,記錄創建時作用域的信息。Java 中內部類本質上就是面向對象的閉包——它不僅包含外圍類對象信息,還自動持有對外圍類對象的引用,可訪問所有成員(含 private)。

回調模式實戰:內部類實現接口回調

場景:Callee2 需實現 Incrementable,但已繼承 MyIncrement 且有同名方法

interface Incrementable {
    void increment();
}

class MyIncrement {
    void increment() { System.out.println("other increment"); }
    static void f(MyIncrement mi) { mi.increment(); }
}

class Callee2 extends MyIncrement {
    private int i = 0;
    private void incr() { i++; System.out.println(i); }
    
    // 內部類實現 Incrementable,避開繼承衝突
    private class Closure implements Incrementable {
        public void increment() { incr(); }
    }
    
    Incrementable getCallbackReference() {
        return new Closure(); // 返回內部類實例作為回調鉤子
    }
}

class Caller {
    private Incrementable callbackReference;
    Caller(Incrementable cbh) { callbackReference = cbh; }
    void go() { callbackReference.increment(); }
}

public class Callbacks {
    public static void main(String[] args) {
        Callee1 c1 = new Callee1();
        Callee2 c2 = new Callee2();
        MyIncrement.f(c2); // 輸出: other increment
        
        Caller caller1 = new Caller(c1);
        Caller caller2 = new Caller(c2.getCallbackReference()); // 獲得 Closure 實例
        
        caller1.go(); // 1
        caller1.go(); // 2
        caller2.go(); // 1
        caller2.go(); // 2
    }
}

核心設計優勢

特性說明
解決繼承衝突外部類已有同名方法時,內部類可獨立實現接口
安全的回調鉤子調用者僅持有接口引用,只能調用 increment(),無法訪問其他內部狀態
封裝性Closure 為 private,外部不可直接實例化
狀態捕獲內部類自動捕獲外部類實例引用,可訪問 incr() 等私有成員

閉包 vs 普通內部類

  • 匿名內部類:最常見的閉包形式,就地實現接口/繼承類
  • Lambda 表達式:Java 8+ 函數式接口的語法糖,本質仍是閉包
  • 變量捕獲規則:只能捕獲 final 或實際上 final 的局部變量

現代替代:Lambda 與方法引用

// Java 8+ 寫法
Caller caller2 = new Caller(c2::incr); // 方法引用
// 或
Caller caller2 = new Caller(() -> c2.incr()); // Lambda

理解內部類閉包機制,是掌握 Java 回調、事件驅動、函數式編程的基石。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved