Example 1-Closure (Closure)
A closure is a callable object (through callback) that records some information from the scope in which it was created
1 Interfaceincrementable {2 voidincrement ();3 }4 5 classCallee1Implementsincrementable {6 Private inti = 0;7 8 @Override9 Public voidincrement () {Teni++; One System.out.println (i); A } - } - the classmyincrement { - Public voidincrement () { -System.out.println ("Other operation"); - } + - Static voidf (myincrement mi) { + mi.increment (); A } at } - - classCallee2extendsmyincrement { - Private inti = 0; - - @Override in Public voidincrement () { - Super. Increment (); toi++; + System.out.println (i); - } the * Private classClosureImplementsincrementable { $ @OverridePanax Notoginseng Public voidincrement () { -Callee2. This. Increment (); the } + } A the incrementable CallBack () { + return NewClosure (); - } $ } $ - classCaller { - Privateincrementable callbackreference; the - Caller (incrementable callbackreference) {Wuyi This. callbackreference =callbackreference; the } - Wu voidGo () { - callbackreference.increment (); About } $ } - - /** - * Keywords: internal class application, Closure (Closure) <br/> A * 1. A closure is a callable object (via callback) that records information from the scope in which it was created <br/> + */ the Public classTest007 { - $ Public Static voidMain (string[] args) { theCallee1 C1 =NewCallee1 (); theC1.increment ();//1 theCallee2 C2 =NewCallee2 (); theMYINCREMENT.F (C2);//Other operation|1 -Caller Caller1 =NewCaller (C1); inCaller1.go ();//2 theCaller Caller2 =NewCaller (C2.callback ()); theCaller2.go ();//Other operation|2 About } the}
Example 2-order of calls in complex cases
1 classEGG2 {2 3 protected classYolk {4 Publicyolk () {5System.out.println ("Egg2.yolk ()");6 }7 8 Public voidf () {9System.out.println ("Egg2.yolk.f ()");Ten } One } A - PrivateYolk y =Newyolk (); - the PublicEgg2 () { -System.out.println ("New Egg2 ()"); - } - + Public voidinsertyolk (Yolk yy) { -y =yy; + } A at Public voidg () { - y.f (); - } - } - - classTest008subextendsEGG2 { in Publictest008sub () { -System.out.println ("AA"); toInsertyolk (Newyolk ()); + } - the Public classYolkextendsEgg2.yolk { * Publicyolk () { $System.out.println ("Bigegg2.yolk ()");Panax Notoginseng } - the Public voidf () { +System.out.println ("Bigegg2.yolk.f ()"); A } the } + } - $ //order of calls in complex cases $ Public classTest008 { - Public Static voidMain (string[] args) { - Newtest008sub (). g (); the //egg2.yolk () - //New Egg2 ()Wuyi //AA the //egg2.yolk () - //bigegg2.yolk () Wu //Bigegg2.yolk.f () - } About}
Java Inner Class (5): application Example