First of all, because Java does not have the concept of pointers, so Java and C + + in the callback function, although the principle is similar, but the implementation method is different.
To tell the truth, if C + + is simple violence directly, Java is more like a little girl minced, I have too many times to understand this usage ....
1.c++
C + + is simple and straightforward, as long as the function address to be called is passed to the function pointer. As follows
#include <iostream>usingnamespace std; void Pig () { " Pig is barking!" " << Endl;} void Dog (void (* call) ()) {call ();} int Main () { dog (pig);}
It is really simple that the function pig () passes its own address to dog () and then calls the function through the function pointer (c + +, the function pointer Plus "()" equals the function that the function pointer points to).
2.java
In Java, the egg hurts, and sometimes it's not that obvious.
This is the project structure, the points are clear, the following is the code
A.java
Package Javaapplication2; Public Interface a { publicvoid bark ();}
B.java
Package Javaapplication2; Public class B { private a dog; Public B (A dog) { this. Dog= dog; Dog.bark (); }}
C.java
Package Javaapplication2; Public class Implements a{ @Override publicvoid bark () { System.out.println ("Haha, I'm happy" ); } }
Zhuhanshu.java
Package Javaapplication2; Public class Zhuhanshu { publicstaticvoid main (string[] args) { new B (new C ());} }
And then, the principle is simple. is b to call a some of the methods to achieve some functions, but, perhaps A's method has been thought out, but temporarily not implemented, so B according to the method in a the return value and the parameters to be passed to use. When it really works, it's time for someone to implement the A method. So, C implements its method. Then, when called in the main function, the instance of C is passed over. If you don't understand it, you can debug it yourself by debugging the IDE's debug function, and you'll soon understand.
Callback functions in C + + and Java