Java interface Callbacks are increasingly used in android. How should I understand them?
It is like a clear relationship between a leader and a subordinate, and three subordinate spies.
1. A subordinate has a meal ......
(Define interface)
2. The leader made a statement, saying that he was interested in the subordinate's meal and that if the subordinate had dinner, what would he do? But the boss is the boss and he cannot keep staring at his subordinates ......
(Implement interfaces and handle listener events)
3. When the leader speaks, the spy goes to the subordinate's place and the leader gives the spy privilege. How can I use it?
(The Connection established on the interface is actually an upward transformation process. The "upcase" spyware is a leader and thus the leader's method is called)
4. Once you have dinner, the spies will notify the leaders and accomplish what kind of things for them.
(Call the methods in the interface through the interface instance)
In this case, you should have a perceptual understanding of the interface callback mechanism.
Interface People {void peopleList ();} class Student implements People {public void peopleList () {System. out. println ("I'm a student. ") ;}} class Teacher implements People {public void peopleList () {System. out. println ("I'm a teacher. ") ;}} public class Example {public static void main (String args []) {People a; // declare the interface variable a = new Student (); // instantiate, store object references in interface variables.. peopleList (); // interface callback a = new Teacher (); // instantiate, the interface variable stores object references. peopleList (); // interface callback }}
Through interfaces, we abstract a large number of methods that are common but have different implementation details, and then implement specific processing in its interface classes. When we call methods through interfaces, you don't have to consider which method to call.
This is a usage, which generally means polymorphism, and communication in components:
For example, Fragment Communication
1. Define an interface in Fragment, declare an instance of the interface, and instantiate the interface as an Activity object in the onAttach () method
2. Within a method in Fragment, the interface instance is used to call the Activity method and communicate with the Activity.
3. The Activity implements interfaces and methods in the structure to implement the callback processing logic.