成员内部类

内部类相当于外部类的一个成员,和其它成员处于同一个级别,因此可以在内部类中直接访问外部类的各个成员(包括私有属性)。
需要注意的是在外部类中要想访问内部类的各个成员(这里也包括内部类的私有属性)就必须先实例化内部类,然后才能访问。对于为什么能访问内部类的私有属性,是因为即使内部类的成员是私有的,但是也是在外部类中,和外部类的其它成员是平等的,只不过被内部类囊括是在内部中,因此访问都必须先实例化。

public class Outerclass {

  private static int outStatic = 0;
  private int out;

  private Outerclass(){
    this.out = 1;
  }
  class Inner{

    private int in;
    private Inner(){
      this.in = 2;
    }

    private void innerVoidMethod(){
      System.out.println(Outerclass.this.outStatic);//0
      System.out.println(Outerclass.this.out);//1
      System.out.println(Inner.this.in);//2
      System.out.println(this.in);//2
      Outerclass.outerStaticMethod();//outerStaticMethod
      Outerclass.this.outerVoidMethod();//outerVoidMethod
    }
    //private static void innerStaticMethod(){} //error,当内部类中有静态方法或者静态成员变量时,一定是静态内部类
  }

  private void outerVoidMethod(){
    System.out.println("outerVoidMethod");
  }
  private static void outerStaticMethod(){
    System.out.println("outerStaticMethod");
  }
  public static void main(String[] args) {
    new Outerclass().new Inner().innerVoidMethod();//内部类的实例需要先实例化外部类
  }
}

 

posted @ 2017-11-23 13:54  tonggc1668  阅读(293)  评论(0)    收藏  举报