Java内部类(Inner Class)

简单的说,内部(inner)类指那些类定义代码被置于其它类定义中的类;而对于一般的、类定义代码不嵌套在其它类定义中的类,称为顶层(top-level)类。对于一个内部类,包含其定义代码的类称为它的外部(outer)类。
<!--[if !supportLists]-->1          <!--[endif]-->Static member class(静态成员类)

类声明中包含“static”关键字的内部类。如以下示例代码,

Inner1/Inner2/Inner3/Inner4就是Outer的四个静态成员类。静态成员类的使用方式与一般顶层类的使用方式基本相同。

Java代码 复制代码
  1. public class  Outer{   
  2.     //just like static method, static member class has public/private/default access privilege levels   
  3.        
  4.     //access privilege level: public    
  5.     public static class Inner1 {   
  6.         public Inner1() {   
  7.             //Static member inner class can access static method of outer class   
  8.             staticMethod();       
  9.             //Compile error: static member inner class can not access instance method of outer class   
  10.             //instanceMethod();     
  11.         }   
  12.     }   
  13.        
  14.     //access privilege level: default    
  15.     static class Inner2 {   
  16.            
  17.     }   
  18.        
  19.     //access privilege level: private    
  20.     private static class Inner3 {   
  21.         //define a nested inner class in another inner class    
  22.         public static class Inner4 {       
  23.         }   
  24.     }   
  25.   
  26.     private static void staticMethod() {   
  27.         //cannot define an inner class in a method   
  28.         /*public static class Inner4() {  
  29.         }*/  
  30.     }   
  31.        
  32.     private void instanceMethod() {   
  33.         //private static member class can be accessed only in its outer class definition scope   
  34.         Inner3 inner3 = new Inner3();   
  35.         //how to use nested inner class   
  36.         Inner3.Inner4 inner4 = new Inner3.Inner4();   
  37.     }   
  38. }   
  39.   
  40. class Test {   
  41.     Outer.Inner1 inner1 = new Outer.Inner1();   
  42.     //Test and Outer are in the same package, so Inner2 can be accessed here   
  43.     Outer.Inner2 inner2 = new Outer.Inner2();    
  44.     //Compile error: Inner3 cannot be accessed here   
  45.     //Outer.Inner3 inner3 = new Outer.Inner3();    
  46. }  




<!--[if !supportLists]-->1.1      <!--[endif]-->静态成员类特性

    * 静态成员类可访问外部类的任一静态字段或静态方法
    * 像静态方法或静态字段一样,静态成员类有public/private/default权限修饰符

<!--[if !supportLists]-->1.2      <!--[endif]-->静态成员类约束

    * 静态成员类不能与外部类重名
    * 像外部类的静态方法一样,不能直接访问外部类的实例字段和实例方法
    * 静态成员类只能定义于外部类的顶层代码或外部类其它静态成员类的顶层代码中(嵌套定义);不能定义于外部类的某个函数中。

<!--[if !supportLists]-->1.3      <!--[endif]-->新增语法

    如示例代码所示,可以以“OuterClass.InnerClass”的方式来引用某个内部类。
<!--[if !supportLists]-->1.4      <!--[endif]-->什么时候使用静态成员类

B为A的辅助类,且只为A所用时,可将B定义为A的静态成员类。例如JDK中的LinkedList类就有Entry静态成员类:

Java代码 复制代码
  1. public class LinkedList<E> extends AbstractSequentialList<E>    
  2.    …;   
  3.    private static class Entry<E> {   
  4.     E element;   
  5.     Entry<E> next;   
  6.     Entry<E> previous;   
  7.   
  8.     Entry(E element, Entry<E> next, Entry<E> previous) {   
  9.         this.element = element;   
  10.         this.next = next;   
  11.         this.previous = previous;   
  12.     }   
  13.     }   
  14.     …;   
  15. }  



   显然,Entry用来表示LinkedList中的一个结点,只被LinkedList自身使用。


<!--[if !supportLists]-->2          <!--[endif]-->Member class(成员类)

一个静态成员类,若去掉“static”关键字,就成为成员类。如下示例代码,Inner1/Inner2/Inner3/Inner4就是Outer的四个成员类

Java代码 复制代码
  1. public class Outer {   
  2.     //just like instance method, member class has public/private/default access privilege levels   
  3.     private int data;   
  4.        
  5.     //access privilege level: public    
  6.     public class Inner1 {   
  7.         private int data;   
  8.         private int data1;   
  9.         public Inner1() {   
  10.             //member class can access its outer class' instance field directly   
  11.             data1 = 1;   
  12.             //itself data field   
  13.             data = 1;   
  14.             //its outer class instance field   
  15.             Outer.this.data = 1;   
  16.         }   
  17.     }   
  18.        
  19.     //access privilege level: default   
  20.     class Inner2 {   
  21.         //can not define static filed, method, class in member class   
  22.         //static int j = 1;   
  23.            
  24.         //but, "static final" compound is allowed    
  25.         static final int CONSTANT = 1;   
  26.     }   
  27.        
  28.     //access privilege level: private    
  29.     private class Inner3 {   
  30.         public class Inner4 {   
  31.                
  32.         }   
  33.     }   
  34.        
  35.     //in fact, Inner5 is not a member class but a static member class   
  36.     interface Inner5 {   
  37.     }   
  38.        
  39.     private static void staticMethod() {   
  40.         //can not create a member class instance directly in outer class' static method   
  41.         //Inner1 inner1 = new Inner1();   
  42.     }   
  43.        
  44.     private void instanceMethod() {   
  45.         //can create a member class instance in outer class' instance method   
  46.         Inner1 inner1 = new Inner1();   
  47.     }   
  48. }   
  49.   
  50. class Test {   
  51.     public Test() {   
  52.         //cannot create member class instance directly in class other than outer class   
  53.         //Outer.Inner2 inner2 = new Outer.Inner2();   
  54.            
  55.         //create a member class instance outside it's outer class   
  56.         Outer outer = new Outer();   
  57.         Outer.Inner1 inner1 = outer.new Inner1();   
  58.     }   
  59. }   
  60.   
  61.    




<!--[if !supportLists]-->2.1      <!--[endif]-->成员类特性

<!--[if !supportLists]-->·        <!--[endif]-->类似于外部类的实例函数,成员类有public/private/default权限修饰符

<!--[if !supportLists]-->·        <!--[endif]-->一个成员类实例必然所属一个外部类实例,成员类可访问外部类的任一个实例字段和实例函数。
<!--[if !supportLists]-->2.2      <!--[endif]-->成员类约束

    * 成员类不能与外部类重名
    * 不能在成员类中定义static字段、方法和类(static final形式的常量定义除外)。因为一个成员类实例必然与一个外部类实例关联,这个static定义完全可以移到其外部类中去
    * 成员类不能是接口(interface)。因为成员类必须能被某个外部类实例实例化,而接口是不能实例化的。事实上,如示例代码所示,如果你以成员类的形式定义一个接口,该接口实际上是一个静态成员类,static关键字对inner interface是内含(implicit)的。

<!--[if !supportLists]-->2.3      <!--[endif]-->新增语法

    一个成员类实例必然所属于其外部类的一个实例,那么如何在成员类内部获得其所属外部类实例呢?如示例代码所示,采用“OuterClass.this”的形式。
<!--[if !supportLists]-->2.4      <!--[endif]-->指定内部类实例所属的外部类实例

内部类实例可在其外部类的实例方法中创建,此新创建内部类实例所属的外

部类实例自然就是创建它的外部类实例方法对应的外部类实例。

          另外,如示例代码所示,对于给定的一个外部类实例outerClass,可以直接创建其内部类实例,语法形式为:

OuterClass.InnerClass innerClass = outerClass.new InnerClass();

<!--[if !supportLists]-->
2.5      <!--[endif]-->什么时候使用成员类

     成员类的显著特性就是成员类能访问它的外部类实例的任意字段与方法。方便一个类对外提供一个公共接口的实现是成员类的典型应用。

       以JDK Collection类库为例,每种Collection类必须提供一个与其对应的Iterator实现以便客户端能以统一的方式遍历任一Collection实例。每种Collection类的Iterator实现就被定义为该Collection类的成员类。例如JDK中AbstractList类的代码片断:

Java代码 复制代码
  1.     
  2. public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {   
  3.     private class Itr implements Iterator<E> {   
  4.          ………;   
  5.     }   
  6.   
  7.      public Iterator<E> iterator() {   
  8.         return new Itr();   
  9.      }   
  10. }  
 



    因为定义在AbstractList中的Itr可访问AbstractList中的任意字段和方法,所以很方便实现Iterator,无需AbstractList对外暴露更多的接口。

    试想,如果没有成员类机制,只有在AbastractList源码之外定义一个实现Iterator的类Itr,该类有一个AbstractList实例成员list,为了Itr能获取list的内部信息以便实现遍历,AbstractList必然要向Itr开放额外的访问接口。
<!--[if !supportLists]-->3          <!--[endif]-->Local class(局部类)

对一个静态成员类,去掉其声明中的“static”关键字,将其定义移入其外部类

的静态方法或静态初始化代码段中就成为了局部静态成员类。

       对一个成员类,将其定义移入其外部类的实例方法或实例初始化代码中就成为了局部成员类。

       局部静态成员类与静态成员类的基本特性相同。例如,都只能访问外部类的静态字段或方法,但不能访问外部类的实例字段和实例方法等。

       局部成员类与成员类的基本特性相同。例如,局部成员类实例必属于其外部类的一个实例,可通过OuterClass.this引用其外部类实例等。

另外,局部类也有其自己的特性,如以下代码所示:




<!--[if !supportLists]-->3.1      <!--[endif]-->局部类特性

如示例代码所示,局部类能且只能访问其所属代码段中的声明为final的局部

变量。为什么只能访问声明为final的局部变量呢?我们知道,局部变量在其所属的代码段(譬如某个函数)执行完毕后就会被回收,而一个局部类的实例却可以在其类定义所属代码段执行完毕后依然存在,如果它可操控非final的局部变量,用户就可以通过该实例修改已不存在的局部变量,无意义。
<!--[if !supportLists]-->3.2      <!--[endif]-->局部类约束

    * 如示例代码所示,内部类只在定义它的代码段中可见,不能在它所属代码段之外的代码中使用;因此也就没有public/private/default权限修饰符(无意义)
    * 不能以局部类形式定义一个接口。局部类只在其所属代码段中可见,定义这样的接口无意义
    * 局部类类名不能与其外部类类名重复

<!--[if !supportLists]-->3.3      <!--[endif]-->什么时候使用局部类

局部类大部分以匿名类的形式使用。

          
<!--[if !supportLists]-->4          <!--[endif]-->Anonymous class(匿名类)

没有类名的局部类就是匿名类。用一条语句完成匿名类的定义与实例创建。例

如如下代码:

Java代码 复制代码
  1. public class Outer {   
  2.     public void instanceMethod() {   
  3.         //define a nonymous class which implements Action interface and creat an instance of it   
  4.         Action action = new Action() {   
  5.             public void doAction() {   
  6.                 System.out.println("a simple anonymous class demo");   
  7.             }};   
  8.         action.doAction();   
  9.            
  10.         //define a nonoymous class which extends BaseClass and create an instance of it   
  11.         new BaseClass(5) {   
  12.             public void printData(){   
  13.                 System.out.println("data = " + getData());   
  14.             }   
  15.         }.printData(); //"data = 5" will be outputed   
  16.     }   
  17. }   
  18.   
  19. interface Action {   
  20.     void doAction();   
  21. }   
  22.   
  23. class BaseClass {   
  24.     private int data;   
  25.        
  26.     public BaseClass (int data) {   
  27.         this.data = data;   
  28.     }   
  29.        
  30.     public int getData() {   
  31.         return data;   
  32.     }   
  33. }  


<!--[if !supportLists]-->4.1      <!--[endif]-->匿名类特性与约束

匿名类是一种特殊的局部类。局部类的特性与约束都适用与它。
<!--[if !supportLists]-->4.2      <!--[endif]-->新增语法
<!--[if !supportLists]-->4.2.1      <!--[endif]-->继承自某个基类的匿名类

new class-name ( [ argument-list ] ) { class-body }



创建匿名类实例时,“argument-list”将被传入其基类(即class-name)对应的构造函数。
<!--[if !supportLists]-->4.2.2      <!--[endif]-->实现某个接口的匿名类

new interface-name () { class-body }


<!--[if !supportLists]-->
4.3      <!--[endif]-->什么时候使用匿名类

    * 该类定义代码段很短
    * 只需要创建该类的一个实例
    * 类的定义代码与类的使用代码紧邻
    * 使用匿名不影响代码的易读性

譬如,如下实现类似与c的callback功能的代码就是匿名类的典型应用:


File f = new File("/src");      // The directory to list

// Now call the list() method with a single FilenameFilter argument
// Define and instantiate an anonymous implementation of FilenameFilter
// as part of the method invocation expression.
String[] filelist = f.list(new FilenameFilter() {
  public boolean accept(File f, String s) { return s.endsWith(".java"); }
}); // Don't forget the parenthesis and semicolon that end the method call!

Java代码 复制代码
  1. public class Outer {   
  2.     private int instanceField;    
  3.     private static int staticField;    
  4.        
  5.     //define a local member class in instance code block   
  6.     {   
  7.         int localVirable1 = 0;   
  8.         final int localVirable2 = 1;   
  9.         class Inner1 {   
  10.             public Inner1() {   
  11.                 //can access its outer class' field and method directly   
  12.                 instanceField = 1;   
  13.                 //use OuterClass.this to get its corresponding outer class instance   
  14.                 Outer.this.instanceField = 1;   
  15.                    
  16.                 //can not access the not final local virable in its containing code block   
  17.                 //System.out.print(localVirable1);   
  18.                    
  19.                 //can access the final local virable in its containing code block   
  20.                 System.out.print(localVirable2);   
  21.             }   
  22.         }           
  23.            
  24.         //local class can not have privilege modifier    
  25.         /*public class inner2 {              
  26.         }*/  
  27.     }   
  28.        
  29.     // define a local static member class in static code block   
  30.     static {   
  31.         class Inner2 {   
  32.             public Inner2() {   
  33.                 staticField = 1;   
  34.                 //can not access instance field and method in a local static member class    
  35.                 //intanceField = 2;   
  36.             }   
  37.         }   
  38.     }   
  39.        
  40.     public void intanceMethod() {   
  41.         //define a local class in its out class' instance method   
  42.         class Inner3 {   
  43.         }   
  44.            
  45.         //local class is visible only in its containning code block   
  46.         //Outer.Inner2 inner2;   
  47.     }   
  48.        
  49.     private static void staticMethod() {   
  50.         //define a local static member class in its out class' static method   
  51.         class Inner4 {       
  52.             public Inner4() {   
  53.                 staticField = 2;   
  54.             }   
  55.         }   
  56.            
  57.         //can not define a interface as a local class   
  58.         /*interface I {  
  59.         }*/  
  60.     }   
  61. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值