Java内部类(5):应用例
例1-闭包(Closure)
闭包是一个可调用的对象(通过Callback),它记录了一些信息,这些信息来自于创建它的作用域
1 interface Incrementable { 2 void increment(); 3 } 4 5 class Callee1 implements Incrementable { 6 private int i = 0; 7 8 @Override 9 public void increment() { 10 i++; 11 System.out.println(i); 12 } 13 } 14 15 class MyIncrement { 16 public void increment() { 17 System.out.println("Other operation"); 18 } 19 20 static void f(MyIncrement mi) { 21 mi.increment(); 22 } 23 } 24 25 class Callee2 extends MyIncrement { 26 private int i = 0; 27 28 @Override 29 public void increment() { 30 super.increment(); 31 i++; 32 System.out.println(i); 33 } 34 35 private class Closure implements Incrementable { 36 @Override 37 public void increment() { 38 Callee2.this.increment(); 39 } 40 } 41 42 Incrementable callBack() { 43 return new Closure(); 44 } 45 } 46 47 class Caller { 48 private Incrementable callbackReference; 49 50 Caller(Incrementable callbackReference) { 51 this.callbackReference = callbackReference; 52 } 53 54 void go() { 55 callbackReference.increment(); 56 } 57 } 58 59 /** 60 * 关键字: 内部类应用, 闭包(Closure)<br/> 61 * 1.闭包是一个可调用的对象(通过Callback),它记录了一些信息,这些信息来自于创建它的作用域<br/> 62 */ 63 public class Test007 { 64 65 public static void main(String[] args) { 66 Callee1 c1 = new Callee1(); 67 c1.increment(); // 1 68 Callee2 c2 = new Callee2(); 69 MyIncrement.f(c2); // Other operation|1 70 Caller caller1 = new Caller(c1); 71 caller1.go(); // 2 72 Caller caller2 = new Caller(c2.callBack()); 73 caller2.go(); // Other operation|2 74 } 75 }
例2-复杂情况下的调用顺序
1 class Egg2 { 2 3 protected class Yolk { 4 public Yolk() { 5 System.out.println("Egg2.Yolk()"); 6 } 7 8 public void f() { 9 System.out.println("Egg2.Yolk.f()"); 10 } 11 } 12 13 private Yolk y = new Yolk(); 14 15 public Egg2() { 16 System.out.println("New Egg2()"); 17 } 18 19 public void insertYolk(Yolk yy) { 20 y = yy; 21 } 22 23 public void g() { 24 y.f(); 25 } 26 } 27 28 class Test008Sub extends Egg2 { 29 public Test008Sub() { 30 System.out.println("AA"); 31 insertYolk(new Yolk()); 32 } 33 34 public class Yolk extends Egg2.Yolk { 35 public Yolk() { 36 System.out.println("BigEgg2.Yolk()"); 37 } 38 39 public void f() { 40 System.out.println("BigEgg2.Yolk.f()"); 41 } 42 } 43 } 44 45 // 复杂情况下的调用顺序 46 public class Test008 { 47 public static void main(String[] args) { 48 new Test008Sub().g(); 49 // Egg2.Yolk() 50 // New Egg2() 51 // AA 52 // Egg2.Yolk() 53 // BigEgg2.Yolk() 54 // BigEgg2.Yolk.f() 55 } 56 }