在Java中,当生成一个内部类的对象时,此对象与制造它的外部类通过外部类的.this保持着联系,因此该内部类对象可以访问其外部类对象的所有成员,包括private成员。

  而该内部类对象对于其他类的对象的访问,遵照常规的访问权限语法,这一点也没有什么特别支持。这里需要探讨的是,外部类以及其他类的对象可以如何访问到某个内部类对象,即内部类的可见性问题。

  下面是一个示例程序Out.java,其中包含了4个不同访问权限的内部类(private,default,protected,public),在每个内部类中,分别包含4个不同访问权限的成员与方法。在外部类Out中提供了得到内部类实例的方法。

  Out.java

package com.zj.main;
 
public class Out {
    public PrivateIn getPrivateIn(){
       return new PrivateIn();
    }
  
    public DefaultIn getDefaultIn(){
       return new DefaultIn();
    }
  
    public ProtectedIn getProtectedIn(){
       return new ProtectedIn();
    }
  
    public PublicIn getPublicIn(){
       return new PublicIn();
    }
  
    private class PrivateIn implements InMethod{
       private int private_arg;
       int default_arg;
       protected int protected_arg;
       public int public_arg;
     
       private void private_method(){};
       void default_method(){};
       protected void protected_method(){};
       public void public_method(){};
    }
  
    class DefaultIn implements InMethod{
       private int private_arg;
       int default_arg;
       protected int protected_arg;
       public int public_arg;
     
       private void private_method(){};
       void default_method(){};
       protected void protected_method(){};
       public void public_method(){};
    }
  
    protected class ProtectedIn implements InMethod{
       private int private_arg;
       int default_arg;
       protected int protected_arg;
       public int public_arg;
     
       private void private_method(){};
       void default_method(){};
       protected void protected_method(){};
       public void public_method(){};
    }
  
    public class PublicIn implements InMethod{
       private int private_arg;
       int default_arg;
       protected int protected_arg;
       public int public_arg;
     
       private void private_method(){};
       void default_method(){};
       protected void protected_method(){};
       public void public_method(){};
    }
 
    public static void main(String[] args){
       //create an outer object
       Out out=new Out();
     
       //create a private inner object by 'new'
       Out.PrivateIn privateIn=out.new PrivateIn();
       privateIn.private_arg=0;
       privateIn.private_method();
     
       // create a private inner object  by 'out's method'
       Out.PrivateIn privateIn2 = out.getPrivateIn();
       privateIn2.private_arg = 0;
       privateIn2.private_method();
    }
}

  所有的4个内部类都实现了一个接口InMethod,该接口的作用在下文中会有讨论。下面先讨论内部类所在的外部类对其内部类对象的访问权限问题。