Java程式設計思想中的一個例子,不是很理解使用閉包的必要性,如果不使用閉包,是不是有些任務就不能完成?繼續探索。
package InnerClass; interface Incrementable { void increment(); } /** 被調1 */ // Very simple to just implement the interface class Callee1 implements Incrementable { private int i = 0; @Override public void increment() { i++; System.out.println("Callee1" + i); } } class MyIncrement { public void increment() { System.out.println("other operation"); } static void f(MyIncrement mi) { mi.increment(); } } // if your class must implement increment() in some other way, you must use an // inner class class Callee2 extends MyIncrement implements Incrementable { private int i = 0; public void increment() { super.increment(); i++; System.out.println("Callee2:" + i); } private class Closure implements Incrementable { public void increment() { System.out.println("內部類實現介面");//1.這句是我加的。 Callee2.this.increment();//2.既然想表達與外部類的不同,此處為何還要呼叫外部類的方法實現同一個功能,造成迷惑 } } Incrementable getCallbackReference() { return new Closure(); } } class Caller { private Incrementable callbarckReference; public Caller(Incrementable chb) { callbarckReference = chb; } void go() { callbarckReference.increment(); } } public class Callbacks { public static void main(String[] args) { Callee1 c1 = new Callee1(); Callee2 c2 = new Callee2(); MyIncrement.f(c2); Caller caller1 = new Caller(c1); Caller caller2 = new Caller(c2.getCallbackReference()); caller1.go(); caller1.go(); caller2.go(); caller2.go(); } }