/*【匿名對象練習】
* 練習:
*/
interface Inter{
void method();
}
class Test{
//補齊代碼。
///*
static class Innter implements Inter{
public void method(){
System.out.println("method run");
}
}
static Inter funtcion(){
System.out.println("function");
return new Innter();
}
//*/
/*
static Inter function(){
//補齊代碼。
return new Inter(){
public void method(){
System.out.println("no name method");
}
};
}
*/
}
public class Test_NoNameNeiBuLei {
public static void main(String[] args) {
//Test.function().method();
/*
* 1、讀到test.funtcion()用類名調用,說明被調用的是一個static修飾的funtcion()方法
* 2、點.method() 可以確定functions【運算完】返回結果是一個對象。而且是Inter類型
* 只有返回來的是一個對象,對象才能調用method()
* 什麼對象又能調用method()呢,必然是Inter的對象,所以返回類型就是Inter
* 這段代碼其實就是:
* Inter in=Test.function();
* in.method()
*/
show(new Inter(){
public void method(){
System.out.println("no name method");
}
});
}
/*什麼時候使用匿名內部對象
*
* 當你使用的方法是參數類型是接口類型的時,該接口,你去查看一下,發現裏面方法不超過3個
* 兩個或一個的時,你可以定義一個匿名內部類,把匿名內部類作爲參數,傳進去。
*/
public static void show(Inter in){
in.method();
}
/*面試題:
* 在main函數中:
* new Object(); 這個是new一個【Object對象】
* new Object(){}這個是Object的【子類對象】 (只有子類才能定義特殊方法。)
*/
}
--------------------------------------------------------------------------------------------------------------------
/*
* 匿名內部類:
就爲簡化書寫,覆蓋方法。 沒有名字的內部類。
* 1、其實就是內部類的簡寫格式。
* 2、定義匿名內部類的前提:
* 內部類必須是繼承一個類或者實現接口。
* 3、匿名內部類的格式: new 父類/接口(){子類方法} (()可以傳參)
* 3、其實匿名內部類就是一個匿名子類對象,而且這個對象有點胖,可以理解爲帶內容的對象。
* 4、匿名對象只能調用方法一次。
* 5、匿名內部類中最好不要超過3個。 就爲簡化書寫,覆蓋方法。多了就複雜了
*/
abstract class AbsDemo{
abstract void show();
}
class Outerr{
int x=3;
/* 【aa】//把該類簡化爲匿名內部類
class Inner extends AbsDemo{
public void show(){
System.out.println("methodd"+x);
}
}
*/
public void function(){
//new Inner().show();
//就是把上面的Inner()用父類替換,並用大括號實現有名字的方法就是:
//new 父類名(){子類內容}.show(); 就是匿名內部對象了
//帶着內容的對象。 是一個對象,AbsDemo的子類對象,已經複寫AbsDemo的方法是【aa】的匿名內部寫法
new AbsDemo(){
//AbsDemo b=new AbsDemo(){
//int num=9; //該句是可以的,應爲是子類的特有的
void show(){
System.out.println("NoName"+x);
}
/*還可以定義子類特有方法,同非匿名對象一樣的,只不過只能調用一次
*
void abc(){
System.out.println("abc"+x);
}*/
}.show();
//b.show();
//b.abc();//編譯失敗 父類沒有該方法。
}
}
public class Demo_NoNameNeiBulei {
public static void main(String[] args) {
new Outerr().function();
}
}
黑馬官網: http://edu.csdn.net/heima