Interface Callback Understanding: First create a good interface, need to use the anonymous internal class implementation interface, called interface callback, the following is the program I designed.
Package callback;
Import java.util.ArrayList;
Import java.util.List;
Import Java.util.Scanner;
Interface
Package callback;
Public interface Callphone {
public void Playphone ();
}
Phonenum class
Package callback;
public class Phonenum {
private String name;
Private Integer num;
Public Phonenum () {
}
Public Phonenum (String name, Integer num) {
THIS.name = name;
This.num = num;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
Public Integer Getnum () {
return num;
}
public void Setnum (Integer num) {
This.num = num;
}
}
public class Test {
private static list<phonenum> List = new arraylist<> ();
public static void Dicall (Callphone callphone) {//Call interface object passed as a parameter
Callphone.playphone (); Interface Object Invocation method
}
public static void Main (string[] args) {
List.add (New Phonenum ("Zhang San", 1357467065));
List.add (New Phonenum ("John Doe", 1343457568));
List.add (New Phonenum ("Yellow Five", 1374563456));
List.add (New Phonenum ("Zhao Liu", 1363457456));
List.add (New Phonenum ("Liu Qi", 1594545456));
Test.dicall (New Callphone () {//Anonymous inner class, implementing interface
@Override
public void Playphone () {
Scanner sc = new Scanner (system.in);
System.out.println ("Please enter the number you want to dial");
int num = Sc.nextint ();
Boolean flag = false;
String name = "";
for (int i = 0; i < list.size (); i++) {
if (flag = List.get (i). Getnum () = = num) {
Name = List.get (i). GetName ();
Break
}
}
if (flag) {
System.out.println ("You are calling" + name);
} else {
System.out.println ("You dialed the number is not saved in the number book, call intact Please save");
}
SYSTEM.OUT.PRINTLN ("Call Complete, Exit dialer");
}
});
}
}
This article is from the "11654700" blog, please be sure to keep this source http://11664700.blog.51cto.com/11654700/1784542
Implementation of Java Base interface callbacks