什么是內部類?
在一個類的內部再定義一個類
class A{int i;class B{//B是A的內部類int j;int funB(){//int result = A.this.i + this.j; 等同于int result = i + j;return result;}}}
對a.java進行編譯后,除了生成A.class外還有個A美元符B.class(內部類所生成的類文件。外部類美元符內部類.class),在B當中可以任意使用(并非擁有)A的成員變量和成員函數,B并非繼承了A
class Test{public static void main(String args[]){A a = new A();//生成內部類對象A.B b = a.new B();a.i = 2;b.j = 4;int result = b.funB();System.out.PRintln(result);}}
生成內部類對象時首先要有外部類:
A a = new A();A.B b = a.new B();
匿名內部類舉例
interface A{public void doSomething();}
class aImp implements A{public void doSomething(){System.out.println("做事");}}
class B{public void fun(A test){System.out.println("B的fun函數");test.doSomething();}}
class Test{public static void main(String args[]){B b = new B();//匿名內部類b.fun(new A(){ //與aImp的區別在于沒有命名,用于實現接口Apublic void doSomething(){System.out.println("開始做事");}});}}
當需要調用B的fun方法時,需要A類型的參數傳入
新聞熱點
疑難解答