I personally think callback is like polymorphism. For example, a boss calls an employee to eat, but each employee may eat different foods. However, the callback is for the interface. In short, object a calls its own method A, and method A receives the parameter B of the Instance B of interface B. In method A, the method C in interface B is executed. This may be a bit difficult to explain. Let's look at an example below.
For example, if a student in the dormitory sets an alarm, all the people in the dormitory can hear it when the alarm rings. However, James is diligent and gets up after hearing the alarm. Li Si is lazy, sleep after hearing the bell. We can regard the ringtone that is sent as an interface. Both Zhang San and Li Si have implemented this "interface". after a certain period of time, the "ringtone" will be triggered ", "ringtones" are called by people, and what people will do is what people do. See the code below.
1. Interface callperson
- Publicinterface callperson {
- Publicpolicactvoid docallperson ();
- }
Defines a "human" method. This interface can be understood as installing an alarm. 2. Class zhangsan
- Publicclass zhangsan implements callperson {
- String name = "zhangsan ";
- Public String getname (){
- Return name;
- }
- @ Override
- Publicvoid docallperson (){
- System. Out. println (getname () + "when I heard the bell, I got up! ");
- }
- }
3. Class Lisi
- Publicclass Lisi implements callperson {
- String name = "Lisi ";
- Public String getname (){
- Return name;
- }
- @ Override
- Publicvoid docallperson (){
- System. Out. println (getname () + "when I heard the bell, I got up! ");
- }
- }
4. Class alarm
- Publicclass alarm {
- // Ring the bell
- Publicvoid ring (callperson ){
- Callperson. docallperson ();
- }
- }
5. The activity then simulates an alarm in the activity and starts to ring.
- Import Android. OS. Bundle;
- Import Android. App. activity;
- Publicclass mainactivity extends activity {
- @ Override
- Publicvoid oncreate (bundle savedinstancestate ){
- Super. oncreate (savedinstancestate );
- Setcontentview (R. layout. layout_main );
- Alarm alarm = new alarm ();
- Zhangsan = new zhangsan ();
- Lisi = new Lisi ();
- // Simulate the scheduled time when the alarm is triggered and then the alarm is triggered.
- Alarm. Ring (zhangsan );
- Alarm. Ring (Lisi );
- }
- }
Finally, let's take a look at the execution results.
- 12-07 21:49:41. 947: INFO/system. Out (6107): zhangsan got up when he heard the bell!
- 12-07 21:49:41. 947: INFO/system. Out (6107): Lisi heard the bell and got up late.