[Go] Java Inner class closure (closure) and callback (callback)

Source: Internet
Author: User

A closure (closure) is a callable object that records information from the scope in which it was created. With this definition, you can see that the inner class is an object-oriented closure because it contains not only information about the perimeter class object (the scope of the inner class), but also a reference to the object of the perimeter class, within which the inner class has permission to manipulate all members, including private members.

one of the most controversial questions in Java is that Java should contain some kind of pointer-like mechanism to allow callbacks (callback). with callbacks, an object can carry some information that allows it to invoke the initial object at a later point in time.

You will see later that this is a very useful concept. If the callback is implemented by pointers, then you can only hope that the programmer will not misuse the pointer. However, you should have learned that Java is more careful and careful, so no pointers are included in the language.


The ability to provide closures through internal classes is an excellent solution that is more flexible and more secure than pointers. See the following example:

 Innerclasses/callbacks.java//Using inner classes for callbacks package innerclasses import static Net.mindview . util.   print.*;   Interface incrementable {void increment ();      }//Very simple to just implement the interface class Callee1 implements incrementable {private int i = 0;      public void Increment () {i++ print (i);      }} class Myincrement {public void increment () {print ("other operation");}   static void F (myincrement mi) {mi.increment ();} }//If your class must implement increment () in//Some other-the-, you must use an inner class:class Callee2 exten      DS myincrement {private int i=0;         public void Increment () {super.increment ();         i++;      print (i); } Private class Closure implements incrementable {public void increment () {//Specify Outer-clas     s method, otherwise//you ' d get a infinite recursion Callee2.this.increment ();    }} 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 Calleel ();         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 (); }   }


Output:

Other operation
1
1
2
Other operation
2
Other operation
3

This example further illustrates the difference between a perimeter class implementing an interface and an inner class implementing this interface. As far as code is concerned, CALLEE1 is a simple solution. Callee2 inherits from Myincrement, which already has a different increment () method and is completely unrelated to the increment () method that the Incrementable interface expects.

So if Callee2 inherits the Myincrement, it cannot cover the increment () method for incrementable purposes, so it can only use the inner class to implement incrementable independently. Also note that when an inner class is created, it is not added to the interface of the perimeter class, nor does it modify the interface of the perimeter class.

Note that in Callee2 except for Getcallbackreference (), the other members are private. To establish any connection with the outside world, interface incrementable is required. Here you can see how interface allows the interface to be completely independent of the implementation of the interface.

The inner class closure implements the incrementable to provide a "hook" to the Callee2--and a secure hook. Whoever gets a reference to this incrementable can only call increment (), except that there is no other function (unlike pointers, which allows you to do a lot of things).

The caller constructor requires a incrementable reference as a parameter (although the callback reference can be caught at any time), and then at some later point, the caller object can use this reference to callback the callee class.

The value of a callback is its flexibility--the ability to dynamically determine what method to invoke at run time.


From: The third edition of Java programming thought

The closure of dynamic language is an eternal topic. The convenience and rapidity of closure in the coding process makes the proponents of dynamic language relish it, while static languages, especially the Java-language fans, will come up with anonymous inner classes that have similar functions in the Java language.

The resulting closure in JavaScript is due to the internal function that is allowed in JavaScript, which is the function declared within a function. Internal function can access local variables in external function, incoming parameters, and other internal function. A closure is formed when an internal function can be referenced outside the external function that contains it. At this point, even if the external function is executed, the internal function can still be executed, and the local variables of the external function used, the parameters passed in, and so on, still retain the value at the end of the external function execution. Here is an example:

function Outer () {    var i=0;    function Inner () {        alert (++i);    }    return Inner;} var inner = Outer (); inner ();


Because a variable outside the function outer inner references a function inner within the function outer, it is said that a closure is created when the function outer's inner function inner referenced by a variable outer the function inner.


What is the effect of closures: in short, the function of closures is that after outer executes and returns, the closure makes the garbage collection mechanism of JavaScript GC not reclaim the resources that outer consumes, because outer's intrinsic function inner execution relies on variables in outer.


A closure is a callable object that records information from the scope in which it was created. With this definition, you can see that the inner class is an object-oriented closure, because it contains not only the information that creates the scope of the inner class, but also a reference to the object of this perimeter class, within which the inner class has permission to manipulate all members, including private members.

C + + has pointer functions that can implement callbacks. With callbacks, an object can carry some information that allows it to invoke the initial object at a later point in time. There are no pointers in Java, and callbacks are implemented by anonymous classes.

An understanding of >>> callbacks <<<

The rationale behind the callbacks is the same as the Hollywood principles, and Don ' t call Me,i ' LL.


Programming, generally use a library or class, you call someone else's API, this call, sometimes this can not meet the needs, you need to register (inject) your own program (such as an object), and then let people in the appropriate time to call you, this is called callback. Observer in design mode is an example: all observers need to register with the subject they care about, and then the topic notifies all observers who subscribe to it and updates it at the appropriate time (when the subject class object's properties change). One of the observers implements the Update method in a unified observer interface.

A callback essentially refers to a class that, although it actually implements a function, does not directly provide the appropriate interface, the client class can obtain this function through the interface of the class's inner class. The inner class itself does not provide a real implementation, just invoke the implementation of the external class. As can be seen, callbacks give full play to the advantages of internal classes having access to the implementation details of external classes.

Above transfer from: http://jiangzhengjun.iteye.com/blog/658354

[Go] Java Inner class closure (closure) and callback (callback)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.