内部类和匿名内部类

1. 什么是内部类

2. 内部类的使用方法

3. 匿名内部类的使用方法

 

1. 什么是内部类

 1 class A{ 2 class B{ 3 } 4 } 

   会生成如下class

 

 

2. 内部类的使用方法

    

 1 class A{
 2     int i;
 3     class B{
 4         int j;
 5         int funB(){
 6             int result = i + j ;
 7             return result;
 8         }
 9     }
10 }
 1 class Test{
 2     public static void main(String args []){
 3         A a = new A();              //生成外部类对象
 4         //A.B b = new A().new B();    //生成内部类对象
 5         A.B b = a.new B();
 6         
 7         a.i = 3 ;
 8         b.j = 1;
 9         int result = b.funB();
10         System.out.println(result);
11     }
12 }

         

 

方法二

 1 interface A{ 2 public void doSomething(); 3 } 

1 class B{
2     public void fun(A a){   //接收A类型的参数
3         System.out.println("B类的fun函数");
4         a.doSomething();
5     } 
6 }
1 class AImpl implements A{
2     public void doSomething(){
3         System.out.println("doSomething");        
4     }
5 }
1 class Test{
2     public static void main(String args []){
3         AImpl al = new AImpl();  //生产AImpl对象            
4         A a = al ;               //向上转型为A类型
5         B b = new B();
6         b.fun(a);                //调用b函数传入A类的a参数即可
7     }
8 }

           

 

 

 3. 匿名内部类的使用方法

 1 interface A{ 2 public void doSomething(); 3 } 

1 class B{
2     public void fun(A a){   //接收A类型的参数
3         System.out.println("B类的fun函数");
4         a.doSomething();
5     } 
6 }
 1 class Test{
 2     public static void main(String args []){
 3         //AImpl al = new AImpl();  //生产AImpl对象            
 4         //A a = al ;               //向上转型为A类型
 5         B b = new B();
 6         b.fun(new A(){   
 7             public void doSomething(){
 8                 System.out.println("hhhhh");   //这部分就相当于上面的AImpl class了,只不过没有名字,所以叫匿名类
 9             }
10         });                
11     }
12 }

 

      

posted @ 2014-05-21 16:26  Mirrorhanman  阅读(369)  评论(0编辑  收藏  举报