?? ?? ?? ???? ?? ??? ?? ???? ?? ???? ??? ??? ? ???? OuterClass.this.medthod()? ?? ????? ???? ?? ?? ??? ???? ??? ? ??? ?? ?????. ??? ??? ????? ??? ? ????. ??? ?? ??? ? ???? ????.
?????? ??? ????. ??? ??? ??? Speaker ?? ??? ??? ???? Perform ???? ???? ??? ?? handlerAction ???? ???? ? ???? ????? Action ??????? ?????? ??? ????? ???. ???? ??. ???? ??? ?? ??? ??????. ??? ?????.
???? ??? ??? ???? ?? ???? ?? ??? ??, ?? ?? ????? ?????? ???? ?? ????? ?? ????. ? ? ?? ????? ???? ??? ? ???? test.this ???? ???? ????
?????. new Speaker().handleAction(new Action(){....
?? ?? ??? test.this? ?? ??? ???, test.this? ??? ??? ???????
???
new Speaker()
? ?? ?? ???? ??? ??? ??? ??? ????. Speakernew Action(){}
? ?? ?? ????? ??? ????. ??? ?? ?????. ??? ??? ?????(??? ??? Test$1??? ?????. this.getClass()? ???? ??? ? ????).
? ??? ???? ?????. ?? ?? ????? ?? {}? ????. new Action(){}
? ??? ??? ???? ????? ?? ?? ???? Test???. new Speaker()
不是匿名內(nèi)部類,它有確切的類名Speakernew Action(){}
是匿名內(nèi)部類,會在編譯的時(shí)候給它一個(gè)類名(我們假定它的類名叫Test,你可以打印this.getClass()看看)
看出兩者的區(qū)別了嗎?匿名內(nèi)部類多出了個(gè){}。
由于new Action(){}
是在test對象的作用域里被創(chuàng)建的,所以它的外部類是Test。
匿名內(nèi)部類也有構(gòu)造器,而且和普通類的構(gòu)造器有點(diǎn)不一樣,編譯的時(shí)候會在匿名內(nèi)部類的構(gòu)造器的參數(shù)列表之前再插入一個(gè)參數(shù),這個(gè)參數(shù)是外部類的對象的引用,編譯之后這個(gè)類長這樣:
public void perform(){
new Speaker().handleAction(new Action(){
@Override
public void action() {
report();//???為什么能調(diào)用report??
}
});
}
new Action(){...}
???
new Action(){...}
? ??? Test$1? ???? ???? ?? Test$1? ?? ??? ?? ??? ???????
???
????? ??? ?? ???? ?? ???? ?? ??? ???? ?? ???? ???? ??? ? ??????