生活随笔
收集整理的這篇文章主要介紹了
java函数回调
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、本質
函數回調本質就是:通過傳遞引用來調用引用指定對象的方法,回調方法一定涉及兩個類,通過方法參數接收另外一個類的引用來調用另外一個類的方法,其實就是一個函數的參數是某個接口的實現類
二、代碼直接解釋
基礎需求,讓室友幫忙寫作業代碼
public class RoomMate {public String
getAnswer(String homework
) {if("1+1=?".equals(homework
)) {return "2";} else {return null
;}}public void getAnswer(String homework
, Student student
) {if("1+1=?".equals(homework
)) {student
.doHomeWork(homework
, "2");} else {student
.doHomeWork(homework
, "(空白)");}}public void getAnswer(String homework
, Work work
) {if("1+1=?".equals(homework
)) {work
.doHomeWork(homework
,"2");} else {work
.doHomeWork(homework
,"(空白)");}}public void getAnswerMyWork(String homework
, Work work
) {System
.out
.println("question is "+homework
);work
.doHomeWorkWithoutParam();}public void askDifficult(String homework
, Work work
) {System
.out
.println("question is "+homework
);work
.doHomeWorkWithoutParam();}
}
public interface Work {default void doHomeWork(String question
, String answer
){}default void doHomeWorkWithoutParam(){};
}
public class WorkImpl implements Work{@Overridepublic void doHomeWork(String question
,String answer
) {if(question
!= null
) {System
.out
.println("作業:"+question
+" 答案:"+ 2);} else {System
.out
.println("作業:"+question
+" 答案:"+ "(空白)");}}
}
public class Student{public void doHomeWork(String homeWork
, String answer
) {System
.out
.println("student.doHomeWork");System
.out
.println("作業:" + homeWork
+ " 答案:" + Objects
.requireNonNullElse(answer
, "(空白)"));}private static void goHome() {System
.out
.println("我先回家");}public static void main(String
[] args
) throws InterruptedException
{Student student
= new Student();String aHomeWork
= "1+1=?";RoomMate roomMate
= new RoomMate();String theAnswer
= roomMate
.getAnswer(aHomeWork
);student
.doHomeWork(aHomeWork
, theAnswer
);roomMate
.getAnswer(aHomeWork
,student
);WorkImpl workImpl
= new WorkImpl();roomMate
.getAnswer(aHomeWork
, workImpl
);roomMate
.getAnswerMyWork(aHomeWork
, new Work() {@Overridepublic void doHomeWorkWithoutParam() {if (aHomeWork
!=null
){System
.out
.println("answer is 2");}}});String hardHomework
= "當x趨向于0,sin(x)/x =?";new Thread(() -> roomMate
.askDifficult(hardHomework
, new Work() {@Overridepublic void doHomeWorkWithoutParam() {if ("1+1=?".equals(hardHomework
)) {System
.out
.println("作業:" + hardHomework
+ " 答案:" + 2);} else if ("當x趨向于0,sin(x)/x =?".equals(hardHomework
)) {System
.out
.print("思考:");for (int i
= 1; i
<= 3; i
++) {System
.out
.print(i
+ "秒 ");try {TimeUnit
.SECONDS
.sleep(1);} catch (InterruptedException e
) {e
.printStackTrace();}}System
.out
.println();System
.out
.println("作業:" + hardHomework
+ " 答案:" + 1);} else {System
.out
.println("作業:" + hardHomework
+ " 答案:" + "(空白)");}}})).start();goHome();}
}
參考文章
總結
以上是生活随笔為你收集整理的java函数回调的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。